程序在Linux上生成核心转储,但在Windows上运行正常

dev*_*vnp 0 c

程序在Linux上生成核心转储,但在Windows上运行正常.知道为什么吗?

#include <stdio.h>

int main() {
    int i, n;
    int count[n];
    int total;
    int value;
    int d;

    printf("Enter the length of array: ");
    scanf("%d", &n);

    //printf ("total of array is %4d \n", n);

    for (i=0; i<=n-1 ; i++ ) {
        printf("Enter the number %d: ", i);
        scanf("%d", &count[i]);
        //  printf ("total of array is %4d \n", n);
    }

    //printf ("total of array is %4d \n", n);

    value = totalcalc( count, n);        
    printf ("total of array is %3d \n", value);

    scanf ("%d", &d);
}

int totalcalc(int count1[], int j)
{
    int  i, total, value;
    //printf (" Entered into function, value of j is %d \n", j);
    value = 0;
    for (i=0; i<=j-1;i++ ) {
        value = value + count1[i];
        //printf ("the value is %d\n", value);
    }
    return value;
}
Run Code Online (Sandbox Code Playgroud)

Tud*_*dor 9

这部分非常可疑:

int i, n;
int count[n];
Run Code Online (Sandbox Code Playgroud)

n显然是单元化的,你正在分配一个大小的数组n.

如果你想要一个动态大小的数组,你可以这样做:

int* count;
printf("Enter the length of array: ");
scanf("%d", &n);

count = malloc(n * sizeof(int)); // dynamically allocate n ints on heap

value = totalcalc( count, n);

printf ("total of array is %3d \n", value);

scanf ("%d", &d);

free(count); // free memory
Run Code Online (Sandbox Code Playgroud)

  • @ user1504633:`int*count`声明一个指向int的指针,它设计用于保存一个内存块,该内存地址指向足以存储`int`的内存块.`malloc`函数分配指定的字节数,并返回指向新分配的内存块的指针.并且`n*sizeof(int)`将`n`乘以`int`的大小(这可能因硬件,系统甚至编译标志的方面而异).我们也想推荐你**[一些好书](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list)**. (2认同)

jwe*_*ich 7

Because int count[n] was declared before n was properly initialized.

  • 是.而你刚刚幸运的是它确实跑了.@ user1504633 (2认同)