0

程序在 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;
}
4

3 回答 3

9

This part is very dubious:

int i, n;
int count[n];

n is clearly unitialized and you're allocating an array of size n.

If you want a dynamic-sized array you could do this:

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
于 2012-10-30T16:30:06.217 回答
7

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

于 2012-10-30T16:29:36.420 回答
3

count正确声明您的数组,请将其声明移到n已阅读的点之外:

仅 C99 解决方案:

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

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

  int count[n]

更灵活(也包括 C99 之前)的解决方案:

#if __STDC_VERSION__ >= 199901L /* going C99 */
# define NEW_ARRAY(t,a,n) t a[n]
# define DELETE_ARRAY(a)
#else
# define NEW_ARRAY(t,a,n) t * a; \ a = malloc((n) * sizeof(t)))
# define DELETE_ARRAY(a) free(a)
#endif

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

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

  {
    NEW_ARRAY(int, count, n);

    ...

    DELETE_ARRAY(count);
  }

  ...
于 2012-10-30T16:36:18.857 回答