0

Here is the structure:

typedef struct {
    int nr_operations;
    int *operations_idxs;
} sensor;

I try to read from a FILE elements in operations_idxs.

I get segmentation fault using this code:

S[i].operations_idxs=(int*)malloc(S[i].nr_operations*sizeof(int));
fread(&S[i].operations_idxs, sizeof(int), S[i].operations_idxs, f);

But works well with this code, reading right data:

S[i].operations_idxs=(int*)malloc(S[i].nr_operations*sizeof(int));
for( j=0; j<S[i].nr_operations; j++) {
    fread(&S[i].operations_idxs[j], sizeof(int), 1, f);
}
Luuk
  • 12,245
  • 5
  • 22
  • 33
  • Please use triple back-quotes before, and after, your code. – Luuk Apr 10 '23 at 13:00
  • I have little knowledge about C, but this might be the problem [size of struct in C](https://stackoverflow.com/questions/1841863/size-of-struct-in-c) – Luuk Apr 10 '23 at 13:04

1 Answers1

0

Well, i didn't see that i used the address of the pointer S[i].operations_idxs as the first argument.

So i had to use this to work:

 S[i].operations_idxs=(int*)malloc(S[i].nr_operations*sizeof(int));
 fread(S[i].operations_idxs, sizeof(int), S[i].operations_idxs, f);
Pascalmh
  • 1,889
  • 1
  • 12
  • 9