【发布时间】:2017-05-31 09:29:44
【问题描述】:
当我多次运行时,以下代码的输出未定义。我想知道为什么输出是未定义的,以及当我尝试将值分配给一个未知边界的数组时会产生什么影响。
#include <stdio.h>
int main()
{
int a[]= {};
int num_of_elements;
int count = 0;
printf("Enter the number of elements:\n");
scanf("%d",&num_of_elements);
printf("Enter the numbers:\n");
for(count=0; count<num_of_elements; ++count)
{
scanf("%d", &a[count]);
}
printf("\n");
for(count=0; count<num_of_elements; count++)
{
printf("%d, ", a[count]);
}
printf("\n");
return 0;
}
在不同时间运行时的输出:
Enter the number of elements:
2
Enter the numbers:
1 2
0, 0,
Enter the number of elements:
3
Enter the numbers:
1 2 3
0, 0, 2,
Enter the number of elements:
4
Enter the numbers:
1 2 3 4
0, 0, 2, 3,
Segmentation fault
Enter the number of elements:
5
Enter the numbers:
1 2 3 4 5
0, 0, 2, 3, 4,
Segmentation fault
【问题讨论】:
-
int a[]= {};没有用 - 您必须在 知道它的大小之后定义数组。 -
贴出的代码无法编译!它会导致编译器输出两条消息:1)
5:12: warning: ISO C forbids empty initializer braces [-Wpedantic]和 2)5:7: error: zero or negative size array 'a'编译时始终启用警告。然后修复这些警告。 (对于gcc,至少使用:-Wall -Wextra -pedantic)
标签: c segmentation-fault undefined-behavior