gpt4 book ai didi

c - 为结构内的结构分配内存

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

typedef struct{
char id[15];
int count;
}hashtag;

typedef struct node{
hashtag *hashtag;
struct node*next;
}*link;

我正在编写一个程序来从句子中读取主题标签,并且我想将它们存储在列表中。我已经定义了这两个结构,我可以读取主题标签并将其传递给下面的函数,但我需要分配内存的帮助才能将字符串复制到列表。

void check_insert(char newh[]){
link x;
//malloc to allocate memory for the string I want to copy

strcpy(x->hashtag->id, newh);
x->hashtag->count += 1;
head = insert_end(head, x->hashtag); //head is a global variable that points to the 1st element of the list
}

最佳答案

您应该在 check_insert 中分配并初始化指针 x,在不先分配的情况下取消引用它并访问其成员是未定义的行为:

void check_insert(char newh[]){
link x = malloc(sizeof *x);
x->hashtag = malloc(sizeof *x->hashtag);

// strcpy(x->hashtag->id, newh); <-- UB if newh is larger than 14 in size
x->hashtag->id[0] = '\0';
strncat(x->hashtag->id, newh, sizeof(x->hashtag->id));
x->hashtag->count = 1;
head = insert_end(head, x->hashtag);
}

关于c - 为结构内的结构分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174723/

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