0

I am trying to allocate a two dimensional array in a function and reading data in a text file but I apparently did something wrong. The data are organised in the file like this :

0.0000 0.0000
0.0001 0.0005
0.0008 0.0004
...

Here is an abstract of my code.

int main(int argc, char*argv[] {
    double **data = NULL; // The two dimensional array I want to create
    int32_t lines = 0;
    errorCode = readDataFile(&data,dataFile,&lines);
    fclose(dataFile);
}

eErrorCode readDataFile(double ***data,FILE * file, int32_t *lines) {
eErrorCode errorCode = E_NO_ERROR;
  if(file == NULL) {
    return E_RETURN_FILE_ERROR;
  }
  while(!feof(file))
  {
    char c = fgetc(file);
    if(c == '\n')
    {
      *lines += 1;
    }
  }
  rewind(file);
  *data = (double **)calloc(*lines, sizeof(double *));
  if(*data == NULL) {
    return E_MALLOC;
  }
  for(int i = 0; i < *lines; i++) {  // *line ~= 111000
    *data[i] = (double *)calloc(2, sizeof(double));
    if(*data[i] == NULL) {
      return E_MALLOC;
    }
    // Debug purpose only
    printf("%p\n",data);           // This works
    printf("%p\n",*data);          // This works too
    printf("%lf\n",*data[0][0]);   // This works too
    printf("%lf\n",*data[1][0]);   // Does not work (Segmentation fault)
    printf("%lf\n",*data[0][1]);   // Does not work (Segmentation fault)
    if(fscanf(file, "%lf %lf\n",data[i][0],data[i][1]) != 2) {
      printf("Problème lecture data\n");
      return E_RETURN_FILE_ERROR;
    }
  }
}

Some help would be very appreciated. Ps: Sorry for the spelling and grammar mistakes.

nadri14
  • 1
  • 1

0 Answers0