2017-03-04 79 views
1

我想從文件創建列表。這是我的代碼。動態分配內存列表中的字符串C

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

struct node { 
    char str1[200]; 
    char str2[200]; 
    char str3[200]; 
    struct node *next; 
}*start=NULL; 

int main(){ 

FILE *fp; 
fp = fopen("file", "r"); 

while(!feof(fp)){ 

    struct node *new_node,*current; 

    new_node=(struct node*)malloc(sizeof(struct node)); 
    fscanf (fp,"%s %s %s",new_node->str1,new_node->str2,new_node->str3); 
    new_node->next=NULL; 


    if(start==NULL) { 
     start=new_node; 
     current=new_node; 
    } 
    else { 
     current->next=new_node; 
     current=new_node; 
    } 
} 

fclose(fp); 
} 

現在我想STR1,STR2,STR3是動態分配的,但如果我用這個代碼,我有這些錯誤(重複成員STR1,STR2,STR3,預計「;」在年底申報清單,類型名稱需要一個說明符或限定符)

struct node { 
char *str1; 
#ERROR 
str1=(char*)malloc(sizeof(char*)*200); 
char *str2; 
#ERROR 
str2=(char*)malloc(sizeof(char*)*200); 
char *str3; 
#ERROR 
str3=(char*)malloc(sizeof(char*)*200); 
struct node *next; 
}*start=NULL; 

我正在使用Xcode。

+1

既不能分配內存也不能初始化結構聲明中的任何結構變量。 –

回答

3

您不能在struct聲明中分配內存。你應該這樣做在你的主代碼:

struct node { 
    char *str; 
}; 

struct node node1; 
node1.str = malloc(STRLENGTH+1); 

而且,sizeof(char *)是不一樣的sizeof(char)。事實上,你可以依靠sizeof(char)始終爲1,並完全保留它。

+0

'STRLENGTH'意味着字符串的_length_,它比需要分配的字符串的_size_小1。建議'STRLENGTH + 1'或'STRSIZE'。 – chux