2015-11-06 116 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