#include <stdio.h>
#include <stdlib.h>
int main() {
int step;
double position[4];
position[0] = 1;
for (step = 1;step<=4;step++){
position[step] = 99;
}
return 0;
}
可以编译没有错误,并且生成的程序可以运行。C:数组错误初始化的奇怪行为
然而,
#include <stdio.h>
#include <stdlib.h>
int main() {
int step;
double position[3];
position[0] = 1;
for (step = 1;step<=3;step++){
position[step] = 99;
}
return 0;
}
也可以编译,但程序不能运行:错误是Abort trap: 6
。
在上述两种情况下,(错误地)初始化数组的大小为1小于我在填for循环的。但为什么4
和3
在这里有所作为?
现在,更有趣的是,
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int main() {
int step;
double position[4];
position[0] = 1;
position[1] = 99;
position[2] = 99;
position[3] = 99;
position[4] = 99;
return 0;
}
甚至不能编译(错误是array index 4 is past the end of the array (which contains 4 elements
)。那么为什么for循环在这里有所作为?
存在'C'没有数组边界检查。它会有未定义的行为。 –
这是**未定义的行为**。标准不保证*任何*;可能有也可能不会有编译错误或运行时错误。它甚至可能会擦除所有数据,因为没有保证。 – ikh
在前两种情况下,将在运行时对数组赋值。但在第三种情况下,它将在编译时。所以它会抛出错误。 – Rajeshkumar