C语言 为结构中的结构分配内存


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] = '';
    strncat(x->hashtag->id, newh, sizeof(x->hashtag->id));
    x->hashtag->count = 1;
    head = insert_end(head, x->hashtag);
}

相关内容

  • 没有找到相关文章