Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 无法解释的行为_C - Fatal编程技术网

C 无法解释的行为

C 无法解释的行为,c,C,最近我开始自学C,所以可能有点新手问题。 我编译了以下命令: #include <stdio.h> int main() { int arr[5]={0}; int arr2[5]={0}; printf("%d\n",arr[5]); //here output: 2130567168 printf("%d\n",arr2[5]); //here output: 0 return 0; } #包括 int main() { int arr[5]={0}; i

最近我开始自学C,所以可能有点新手问题。 我编译了以下命令:

#include <stdio.h>

int main()
{
  int arr[5]={0};
  int arr2[5]={0};
  printf("%d\n",arr[5]); //here output: 2130567168
  printf("%d\n",arr2[5]); //here output: 0
  return 0;
}
#包括
int main()
{
int arr[5]={0};
int arr2[5]={0};
printf(“%d\n”,arr[5]);//此处输出:2130567168
printf(“%d\n”,arr2[5]);//此处输出:0
返回0;
}

有人能解释不同输出的原因吗?

您正在访问超出声明范围的数据。已声明为
arr[5]
的数组的索引范围从0…4开始,但您希望访问既未定义也未分配的arr[5]。因此,根据要访问的内存“单元”的值,您会得到随机答案,在本例中为0和其他数字。

这两个
printf
s都会产生未定义的行为,因为它们访问的元素超过了相应数组的末尾。C数组的索引的有效范围为0到
length-1
,因此对于程序中的两个数组,该范围应为0..4,包括在内


访问索引5处的元素超过了数组的末尾,因此不同的编译器可能会产生不同的行为,从打印垃圾到崩溃。

这是未定义的行为。C不在数组上执行。

C规范()第6.7.8.21节描述了C中此代码的行为:对于没有指定值的元素,编译器将指针初始化为NULL,将算术类型初始化为零(并递归地将其应用于聚合)


请参考上述文件了解。另外,我不是直接在这里发布答案,因为你们是新手,因为我不想用勺子喂你们。快乐学习

以后,请在编译器上启用警告。例如,对于GCC,这将是
-Wall

main.cpp:7:29: warning: array subscript is above array bounds [-Warray-bounds]
         printf("%d\n",arr[5]); //here output: 2130567168
                             ^
main.cpp:8:30: warning: array subscript is above array bounds [-Warray-bounds]
         printf("%d\n",arr2[5]); //here output: 0
请注意,C标准表示这是未定义的行为:

§J.2

1在以下情况下,该行为未定义:

-数组下标超出范围,即使对象明显不在范围内 可通过给定的下标访问(如左值表达式中的下标 a[1][7]鉴于声明int a[4][5])(6.5.6)


接受您通常的讲座。

您是否意识到您正在访问超出范围的阵列?您只为这两个文件分配了5个整数的空间,但您正在尝试访问第六个整数。鼻魔的可能副本更具娱乐性,而且它们并不是严格地介于垃圾输出和崩溃之间。为什么有人在没有墙的情况下编译?使用fortran90的thanx仍然不习惯语法。为什么第二个返回0?因为你很幸运?运行程序几次,看看输出。我做了,但它仍然是一样的。。。这就是让我困惑的东西,没有什么是确定性的。