[英]Assigning values to array of struct pointers
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. 我正在尝试制作一个结构指针数组,以便可以使用null终止该数组的末尾并能够遍历该结构数组。
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;
}
You allocated the space for the array, but not for each individual struct that the pointers in the array point to: 您为数组分配了空间,但没有为数组中的指针指向的每个单独的结构分配空间:
while(fgets(str, 60, f)){
char *tok = strtok(str, ",/n");
a[i] = malloc( sizeof( s ) );
//...
Other notes: 其他说明:
malloc()
. malloc()
的结果。 const char* delim = ",\\n"
) instead of retyping the same sequence. const char* delim = ",\\n"
),而不是重新键入相同的序列。 It helps to prevent errors, like typing ",/n"
, when you mean ",\\n"
which you did. ",\\n"
时键入",/n"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.