我可以从一个位置更改结构成员,但不能从另一个位置更改结构成员

I can alter a struct member from one location but not from the other

我正在尝试用 C 实现一个链表 - 从简单开始,一个列表包含一个节点。但是,我在尝试向节点添加数据时偶然发现了一些问题。到目前为止,这是我的实现:

struct mylist_node {
  int data;
};

struct mylist {
  struct mylist_node *head_pt;
};

void mylist_init(struct mylist* l){
    struct mylist_node head_node;
    head_node.data = 5; //First try
    l->head_pt = &head_node;
    l->head_pt->data = 5; //Second try
};

还有我的主要方法:

int main()
{
    struct mylist ml, *ml_pointer;
    ml_pointer = &ml;
    mylist_init(ml_pointer);

    printf("%d\n", ml_pointer->head_pt->data);
    ml_pointer->head_pt->data = 4;
    printf("%d\n", ml_pointer->head_pt->data);

    return 0;
}

这应该打印出来

5
4

如果我对指针的了解是正确的。但是,它打印出

0
4

如您所见,我尝试在 mylist_init 方法中设置节点数据两次。两者似乎都不起作用 - 同时,从我的主要方法写入和读取它工作得很好。我做错了什么?

mylist_init 中,您将局部变量的地址存储在 l 指向的结构中。当函数 returns 时,该变量超出范围,因此它占用的内存不再有效,因此以前指向它的指针现在指向无效位置。返回局部变量的地址取消引用该地址会调用未定义的行为。

您的函数需要使用 malloc 动态分配内存,因此内存在函数 returns 时仍然有效。

void mylist_init(struct mylist* l){
    struct mylist_node *head_node = malloc(sizeof(*head_node));
    l->head_pt = head_node;
    l->head_pt->data = 5; 
};

此外,不要忘记 free 使用完内存后。

对于初学者,您必须为您的节点分配内存,您的节点是堆栈上的局部变量,在函数退出后可能会被覆盖。

void mylist_init(struct mylist* l)
{
    struct mylist_node *head_node = (struct mylist_node *)malloc(sizeof(struct mylist_node));
    head_node.data = 5; //First try
    l->head_pt = head_node;
};