c - 分段故障;初学者

标签 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 */
....

这就是我认为我的问题所在。但我不知道为什么会出现错误。语法正确吗?

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/

相关文章:

c++ - 这个严格的别名示例是否正确?

c++ - c(linux)中的函数问题

c - 尝试从文本文件中读取数据,从中创建结构,并将字段打印到标准输出

c - 多个节点上的 MPI_Bcast 错误

c++ - 用户定义指针双端队列中的段错误

c++ - 如何将链表的节点直接链接到节点指针?

无法访问我的 .h 文件中定义的结构中的 3d 数组

c++ - 如何以编程方式修改 Open/Libreoffice odt 文档?

c - 如何找到任何PC的端口号?

c++ - 为什么我的 Qt 插槽会导致我的程序崩溃?