首页 > 解决方案 > 访问结构体值,改变结构体值

问题描述

当我遇到这个奇怪的问题时,我试图了解指针在 c 中是如何工作的。

现在,我想建立一个链表。我做的第一件事是添加 add 函数。一旦函数将一个节点添加到列表的最后一个节点(它成功)

typedef struct linkedLists{
    int x;
    struct linkedLists *next;
    //int (*add)(int) = add;
}linkedList;

void addF(linkedList *l, int y){
    linkedList adder = {.x=y};
    l->next = &adder;
    return;
}

int main(int argc, char** argv) {
    linkedList list = {.x=2,.next=NULL};
    printf("%d\n",list.x);

    addF(&list,3);

    printf("%d\n",list.x);
    // If you comment this line the result changes to what it's  
    //expected

    printf("%d\n",(*list.next).x);

    return (EXIT_SUCCESS);
}

如果我跑

printf("%d\n",(*list.next).x); 

我得到 3,这是所需的。但是,如果我运行

printf("%d\n",list.x);
printf("%d\n",(*list.next).x);

我得到:2 随机数

标签: cpointersstruct

解决方案


l->nextaddF()分配了一个指针值,一旦结束,该值将很快变为无效。结果:未定义的行为

void addF(linkedList *l, int y){
    linkedList adder = {.x=y};  // adder is local
    l->next = &adder;  
    return;
}

更有意义的是遍历链表(假设它至少有一个节点)并附加一个新节点。

void addF_alt(linkedList *l, int y) {
  while (l->next) {
    l = l->next;
  }
  l->next = malloc(sizeof *(l->next));
  if (l->next) {
    l = l->next;
    l->next = NULL;
    l->x = y;
  }
}

更常见的是通过函数进行所有节点追加。

TBD code

推荐阅读