[英]Allocating a struct and saving a string in it
I'm having issues with getting create to hold firstE here: 我在这里获得创建以保留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;
}
I'm having a problem with the memory allocation for create->data
. 我在create->data
的内存分配方面遇到问题。 I am trying to get it to hold the value of FirstE
but I can't seem to get it. 我试图使其保持FirstE
的价值,但我似乎无法FirstE
。
I have to guess your problem since there is no struct definition. 由于没有结构定义,我不得不猜测您的问题。 Your second malloc
allocates memory for a field of the same type as the struct. 您的第二个malloc
为与该结构相同类型的字段分配内存。 But because you use strcpy
to copy from the function argument, I suggest this line is incorrect, it allocates the wrong amount of memory 但是因为您使用strcpy
从函数参数复制,所以我建议这一行是不正确的,它分配了错误的内存量
create->data = malloc(sizeof(struct node));
strcpy(create->data, firstE);
Since you copy the string argument to this field, I suggest this 由于您将字符串参数复制到此字段,因此我建议这样做
create->data = malloc(1 + strlen(firstE));
strcpy(create->data, firstE);
The 1 +
is to allow for the string terminator. 1 +
是允许使用字符串终止符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.