0
我想要做一個結構指針數組,所以我可以用null終止數組的末尾,並且能夠通過結構數組運行。賦值給結構指針數組
我最初得到了一個可以工作的結構數組,但是當將結構數組更改爲結構指針數組時,當嘗試通過取消引用來分配或訪問結構值時會出現分段錯誤。
我想知道我做錯了什麼。
#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;
}
這工作,也是有道理的。 – TheWinterSnow