簡體   English   中英

使用fscanf從文件中的數據生成數組時出現C段錯誤

[英]C segfault while using fscanf to make array from datas in a file

我已經嘗試找到解決問題的方法,但我沒有找到,所以我在這里發布。

我想讀取一個文件然后從我得到的數據創建兩個1D數組 該文件是這樣的:

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

這是我的檔案:

7
1.  4.1
2.  8.2
5  19.5
12 50
20  78
30  50.05
50  5

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;
    }

這就是程序給我的回報:

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

感謝您的幫助和關注!

沒關系,我找到了解決方案。
只是我使用malloc非常糟糕。 我寫

x = malloc(n * sizeof(int));

什么時候我應該寫

x = malloc(n * sizeof(double));

我寫的代碼給我一個分段錯誤? 由於xy內存分配不正確,因此分段故障導致語句如下所示。

x = malloc(n * sizeof(int));
y = malloc(n * sizeof(int));

(因為在大多數機器上sizeof(double)大於sizeof(int)所以一段時間后數組元素沒有足夠的空間)

它應該是

x = malloc(n * sizeof(*x)); /* it works for any type */
y = malloc(n * sizeof(*y));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM