2015-11-06 117 views
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; 
} 
+0

这工作,也是有道理的。 – TheWinterSnow

回答

1

你分配给数组的空间,而不是每个人结构,在阵列点的指针:

while(fgets(str, 60, f)){ 

    char *tok = strtok(str, ",/n"); 

    a[i] = malloc(sizeof(s)); 
    //... 

其他说明:

  • 在C,you should not cast the result of malloc().
  • 由于您正在重新使用分隔符字符串,因此最好将其存储在变量(const char* delim = ",\n")中,而不是重新输入相同的序列。它有助于防止错误,如打字",/n",当您的意思是",\n"你做了。
+0

太棒了,那样做了。 – TheWinterSnow