C : Acessing a structure within a structure

标签 c pointers structure

typedef struct mensagem
{
    int sender ;
    int receiver ;
    char *text ;
} *Item ;


typedef struct node 
{
    Item item ;
    struct node *next ;
} *link ;

link init(char* text)
{
    link x = (link) malloc(sizeof(struct node));
    (x->item->text) = (char*) malloc(sizeof(char)*(strlen(text)+1));
    strcpy(x->item->text, text);
    x->next = NULL;
    return x;
}

我打算使用 item 内的数据,但我在线上遇到了段错误:

(x->item->text) = (char*) malloc(sizeof(char)*(strlen(text)+1));

我对 C 和指针相当陌生,但我在这里找不到问题。

最佳答案

您尚未为 x->item 指向的结构分配内存。添加

x->item = malloc(sizeof (struct mensamam));

在其他 malloc 之前。

关于C : Acessing a structure within a structure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23574844/

相关文章:

C中的代码覆盖率

c - 如何在 mini-shell 中处理信号 Ctrl + Z。 C

c++ - 从指针指向内存的二进制文件中读取结构

c - 编写接受指针变量并将值从文件分配给 C 结构的函数

gwt - 使用 Maven 将 GWT 源代码整合到 WAR 中的最佳实践

c++ - 结构体(数组)中出现次数最多的数字

c - 如何使用 ARM64 执行多项式乘法?

c - 在 C 中打印节点时出错?

c - 为什么我使用 memcpy() 时会出现无效写入 (Valgrind)?

python - 在 Python 中正确丢弃指向 mmap 内存的 ctypes 指针