c - 访问结构体值,改变结构体值
问题描述
当我遇到这个奇怪的问题时,我试图了解指针在 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 随机数
解决方案
l->next
addF()
分配了一个指针值,一旦结束,该值将很快变为无效。结果:未定义的行为。
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
推荐阅读
- arrays - 如果列、行和单元格值都匹配条件,我如何对值求和?
- java - Anylogic - 在启动时通过控制编辑框更改资源集数量
- python - Kivy Popup 出现在函数运行之后而不是之前
- android - 如何在导航抽屉中将菜单与列表视图结合起来?
- python - 减少 Matplotlib 中面积图中的 x 轴条目
- android - 在 Flutter 本地通知中调用 HTTP 请求
- azure - 如何从 AAS 模型中解决此数据网关错误?
- ios - iOS TrueDepth 帧到点云
- python - Django:ORA:01461:只能绑定 LONG 值以插入 LONG 列
- javascript - 如何在指定数组中推送 null