使用fscanf从文件中的数据生成数组时出现C段错误

Lut*_*ose 2 c arrays scanf segmentation-fault

我已经尝试找到解决问题的方法,但我没有找到,所以我在这里发布.

我想读取一个文件然后从我得到的数据创建两个1D数组.该文件是这样的:

  • 第一行:要收集的数据数量
  • 其他行:我想得到的数据

这是我的档案:

7
1.  4.1
2.  8.2
5  19.5
12 50
20  78
30  50.05
50  5
Run Code Online (Sandbox Code Playgroud)

7是我想要获得的行数(我想要从1到50的所有行).

我写的代码给我一个分段错误,但我不明白为什么.
这是我写的:

    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h> 

    int main(void)
    {
      /* DECLARATION OF CONSTANTS AND VARIABLES */
      FILE* fichier = NULL;
      double* x = NULL;
      double* y = NULL;
      int k,n = 0;

     /* OPENING FILE */
      fichier = fopen("donnees1.txt", "r+");

          if (fichier != NULL)
             {
              fscanf(fichier, "%d", &n);

              /* creating dynamic array of x and y */
              x = malloc(n * sizeof(int));
              y = malloc(n * sizeof(int));

              if (x == NULL)
                 {
                  printf("failed to allocate.\n");
                  exit(0);
                 }

              for(k = 0; k < n; k++)
                 {
                  fscanf(fichier, "%lf %lf", &x[k], &y[k]);
                  printf("%lf %lf\n", x[k],y[k]);
                 }
              /* Closing file */
              fclose(fichier);
             }
          else
            {
             printf("Cannot open the file.\n");
            }

      /* Freeing memory */
      free(x);
      free(y);
      return 0;
    }
Run Code Online (Sandbox Code Playgroud)

这就是程序给我的回报:

1.000000 4.100000
2.000000 8.200000
5.000000 19.500000
12.000000 50.000000
20.000000 78.000000
30.000000 50.050000
50.000000 5.000000
Segmentation fault
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助和关注!

Lut*_*ose 5

没关系,我找到了解决方案.
只是我使用malloc非常糟糕.我写

x = malloc(n * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

什么时候我应该写

x = malloc(n * sizeof(double));
Run Code Online (Sandbox Code Playgroud)

  • 更好,它应该是"x = malloc(n*sizeof(*x))"并且你不能有不匹配的类型,即使你改变了"x"的类型 (2认同)

Ach*_*hal 5

我写的代码给我一个分段错误?分段故障导致语句在下面作为内存分配x并且y不正确.

x = malloc(n * sizeof(int));
y = malloc(n * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

(因为在大多数机器sizeof(double)上都比较大,sizeof(int)所以一段时间后阵列元素没有足够的空间)

它应该是

x = malloc(n * sizeof(*x)); /* it works for any type */
y = malloc(n * sizeof(*y));
Run Code Online (Sandbox Code Playgroud)