我想知道c中的數組是如何工作的。所以我正在實現一些基本的數組概念。當我運行程序時,我得到了確切的輸出,但在輸出結束時它說分段錯誤。打印輸出時出現分段錯誤
int main(void)
{
int a[] = {};
printf("Enter the number:");
int n = get_int();
int m = 0;
for(int i = 0; i<n; i++)
{
printf("insert:");
m = get_int();
a[i] = m;
}
for(int j = 0; j < n; j++)
{
printf("%d\n", a[j]);
}
}
輸出:
Enter the number:3
insert:1
insert:2
insert:3
1
2
3
~/workspace/ $ ./arr_test
Enter the number:5
insert:1
insert:2
insert:3
insert:4
insert:5
1
2
3
4
5
Segmentation fault
看到它的尺寸爲3它並不顯示segmentation fault
第一輸出但對於第二個具有的尺寸爲5它顯示。所以爲什麼會發生這種情況,我犯了什麼錯誤
int a [] = {};'是標準C中的錯誤。我建議在標準兼容模式下操作您的編譯器,以免在編譯時而不是運行時出錯。 –