當我多次運行時,以下代碼的輸出未定義。我想知道爲什麼輸出未定義,以及當我嘗試爲未知邊界數組賦值時會有什麼含義。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