我不明白我在哪里遇到错误。我相信这是在用户从菜单中输入选项之一的最后部分。
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 */
....
这就是我认为我的问题所在。但我不知道为什么会出现错误。语法正确吗?
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;
}
最佳答案
int size; /* array size */
double data[size]; /* array variable */
这就是问题 - size
未初始化,data
数组的大小是随机的。
您应该首先从用户那里读取大小
,然后使用malloc
动态创建数组。像这样的东西:
scanf("%d",&size);
//...
double* data = (double*)malloc( size * sizeof( double ) );
// NOTE: don't forget the `free` this memory later
关于c - 分段故障;初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20180485/