2017-03-30 108 views
0

我想知道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它显示。所以为什么会发生这种情况,我犯了什么错误

+0

int a [] = {};'是标准C中的错误。我建议在标准兼容模式下操作您的编译器,以免在编译时而不是运行时出错。 –

回答

3

您需要为阵列分配内存。喜欢的东西:

int main(void) { 
    int *a; 
    ... 
    int n = get_int(); 
    ... 
    a = malloc(n * sizeof(int)); 
    if (!a) { 
     // Add error handling here 
    } 
    ... 
} 
+0

或者只是'int a [n];'在读完之后n – immibis

1

如果你知道你想提前数组的大小,宣布它像int a[128];,而不是仅仅int a[];所以a在指数0127将是安全的写(以及随后读取)。

如果要在运行时声明大小为n的数组,请使用int a[] = malloc(n * sizeof(int));int *a = malloc(n * sizeof(int));。在使用它之前,请确保a不是NULL,并且请记住在完成此操作后请致电free(a);以避免内存泄漏。

+0

我现在把a的大小分配到了128位,但是它没有显示出'段错误'。但我如何让'a'分配它自己的大小。 – pkarthicbz

+0

您没有分配128 *位*的大小。您分配了128 * 4字节。 –