2017-03-04 5 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'は、文字列の_長さを意味します。これは、割り当てが必要な文字列の_size_よりも1小さい値です。 'STRLENGTH + 1'または' STRSIZE'を提案してください。 – chux

関連する問題