I am trying to make an Array of struct pointers so I can terminate the end of the array with null and be able to run through the array of structs.
I originally got an array of structs working but when changing the array of structs into an array of struct pointers I get a segmentation fault when trying to assign or access values of the structs by dereferencing.
I like to know what I am doing wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s{
int a;
char *b;
int c;
int d;
}s;
s** readStruct(){
FILE *f = fopen("file.csv", "r");
if(!f){
printf("Can't open file\n");
exit(1);
}
//An array of struct pointers of size 50
s **x = (s **)malloc(50 * sizeof(s *));
char str[60];
int i = 0;
//Loop through each line of the file while !EOF
//copy each line to string for tokenizing
while(fgets(str, 60, f)){
char *tok = strtok(str, ",/n");
// segmentation fault happens here:
x[i]->a = atoi(tok);
// also happens here too:
printf("%d\n", x[i]->a);
tok = strtok(NULL, tok);
// segmentation fault would result here:
strcpy(x[i]->b, tok);
tok = strtok(NULL, ",\n");
// and here:
x[i]->c = atoi(tok);
tok = strtok(NULL, ",\n");
// and here:
x[i]->d = atoi(tok);
i++;
}
return x;
}
int void main(){
s **x = readStruct();
for(int i = 0; (x + i) < NULL; i++){
printf("%d\n", x[idx]->a);
printf("%s\n", x[idx]->b);
printf("%d\n", x[idx]->c);
printf("%d\n", x[idx]->d);
printf("\n");
}
return 0;
}