我在这里遇到了创建firstE的问题:
struct node {
char * data;
struct node * next;
};
struct node * createList(char * firstE){
struct node *create;
create = malloc(sizeof(struct node));
create->data = malloc(sizeof(struct node));
strcpy(create->data, firstE);
create->next = NULL;
return create;
}
我对create->data
的内存分配有问题。我试图让它保持FirstE
的值,但我似乎不能得到它
我不得不猜测你的问题,因为没有结构定义。您的第二个malloc
为与结构相同类型的字段分配内存。但是因为您使用strcpy
从函数参数复制,所以我认为这一行是不正确的,它分配了错误的内存量
create->data = malloc(sizeof(struct node));
strcpy(create->data, firstE);
由于您将字符串参数复制到此字段,因此我建议使用
create->data = malloc(1 + strlen(firstE));
strcpy(create->data, firstE);
1 +
允许字符串结束符