我正在尝试创建一个struct指针数组,这样我就可以使用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;
}
答案 0 :(得分:1)
您为数组分配了空间,但没有为数组中指针指向的每个结构分配:
vip
其他说明:
malloc()
. while(fgets(str, 60, f)){
char *tok = strtok(str, ",/n");
a[i] = malloc( sizeof( s ) );
//...
)中,而不是重新输入相同的序列。当您指的是const char* delim = ",\n"
时,它有助于防止出现错误,例如键入",/n"
。