程序在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)
这部分非常可疑:
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)
Because int count[n] was declared before n was properly initialized.