分段故障; 初学者

leo*_*vic -1 c segmentation-fault

我不明白我在哪里得到错误.我相信它是在用户输入菜单中的一个选项的最后部分.

int main()
{
    int i,j; /* counter variables */
    int size; /* array size */
    double data[size]; /* array variable */
    int o; /* response variable */
    printf("\nHow many numbers do you have in your data set?\n"); /* initial instructions */
    scanf("%d",&size); /* */
    printf("\nPlease enter those numbers.\n"); /* data set */
    for(i=0;i<size;i++){ /* loop to correspond a data point to an element */
        scanf("%lf",&data[i]); /* */
}

/* menu system */
printf("\nNow, please select the following operations:"); /* intro */
printf(" . . . "); /* the menu choices */
....
Run Code Online (Sandbox Code Playgroud)

这就是我认为我的问题所在.但我不知道为什么它会出现错误.语法合适吗?

scanf("%d",&o); /* */
if(o==1){  /* Displaying the data set*/
    for(j=0;j<size;j++){ /* loop to display each element of the array*/
        printf("\n%g,",data[j]); /* displaying the array */
    }
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*rov 6

int size; /* array size */
double data[size]; /* array variable */
Run Code Online (Sandbox Code Playgroud)

这是问题 - size未初始化,data数组的大小是随机的.

您应size首先从用户读取,然后使用动态创建数组malloc.就像是:

scanf("%d",&size);
//...
double* data = (double*)malloc( size * sizeof( double ) );
// NOTE: don't forget the `free` this memory later
Run Code Online (Sandbox Code Playgroud)