[英]Dynamically memory allocation of a string in a list 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。
您無法在struct
聲明中分配內存。 您應該在主代碼中執行此操作:
struct node {
char *str;
};
struct node node1;
node1.str = malloc(STRLENGTH+1);
另外, sizeof(char *)
與sizeof(char)
。 實際上,您可以依賴sizeof(char)
始終為1,並將其完全保留。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.