gpt4 book ai didi

c - 结构体中字符串的初始化

转载 作者:行者123 更新时间:2023-11-30 16:10:10 25 4
gpt4 key购买 nike

struct Person{
char *name;
int numb;
char *var;
};

struct Node{
struct Person *data;
struct Node *next;
struct Node *prev;
};


int main() {

head=(struct Node*)(malloc(sizeof(struct Node)));//
tail=(struct Node*)(malloc(sizeof(struct Node)));//These two are global variables and they are initialized with null above.

struct Person *a1=(struct Person*)(malloc(sizeof(struct Person)));
char is[]="nameee";
strcpy(a1->name,is);

printf("%s\n",a1->name);



return 0;
}

为什么我会遇到该代码的段错误?我创建了一个存储 Person 的双向链表,但是当我用字符串初始化该结构时,此代码出现错误。

最佳答案

struct Person *a1 = malloc(sizeof(struct Person));
char is[] = "nameee";
strcpy(a1->name,is);

strcpy 将字符串复制到内存位置(在本例中为 a1->name);它需要被分配。 a1->name 的值未初始化,因此您正在内存中未定义的位置写入。

您需要为其分配空间,例如:

struct Person *a1 = malloc(sizeof(struct Person));
char is[] = "nameee";
a1->name = malloc(strlen(is) + 1);
strcpy(a1->name,is);

或者,使用strdup

关于c - 结构体中字符串的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58951732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com