当我多次运行时,以下代码的输出未定义。我想知道为什么输出未定义,以及当我尝试为未知边界数组赋值时会有什么含义。C编程中未知绑定用法的数组
#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 [] = {};'是没有用的 - 你必须在*知道它的大小后定义数组*。 –
https://stackoverflow.com/questions/1677157/can-size-of-array-be-determined-at-run-time-in-c – rsp
发布的代码不能编译!它会导致编译器输出两条消息:1)'5:12:警告:ISO C禁止空初始化括号[-Wpedantic]'和2)'5:7:错误:零或负大小数组'a''编译时始终启用警告。然后修复这些警告。 (对于'gcc',最低限度使用:'-Wall -Wextra -pedantic') – user3629249