c - 指针丢失引用的问题
问题描述
我正在尝试做一棵孩子和父亲的树,但是当孩子出生在一个函数中时,我失去了对孩子的提及,这里将举一个狗的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
typedef struct Dog{
int id;
double amound_of_bones;
int *bones;
int *gifts;
struct Dog *other_dog;
}Dog;
void have_children(Dog *father){
Dog pancho;
pancho.id=5;
pancho.amound_of_bones=1544.5;
(*father).other_dog=&pancho;
}
int main(int argc, char *argv[]) {
Dog pepi;
have_children(&pepi);
printf("the dog id: %d, have %f bones\n",(*pepi.other_dog).id,(*pepi.other_dog).amound_of_bones);
printf("the dog id: %d, have %f bones\n",(*pepi.other_dog).id,(*pepi.other_dog).amound_of_bones);
return 1;
}
这是奇怪的输出:
the dog id: 5, have 1544.500000 bones
the dog id: 0, have 0.000000 bones
你会看到第一个输出顺利,但另一个丢失了参考,我不知道如何解决它
解决方案
Dog pancho;
是have_children()
函数中的局部变量。当函数返回时,该内存被释放。您保存了一个指向不再有效的内存的指针。此行为未定义。
推荐阅读
- javascript - 将逗号分隔的字符串转换为逗号分隔的数字
- javascript - 导入对象并在数组中使用它会使第一项未定义?
- apache-spark - Sparkdl 故障排除 Py4JJavaError: 调用 o99.collectToPython 时出错
- jquery - 添加 jquery 生成的
用于围绕两个 jquery 生成的 div 的容器 - javascript - 将 package.json 更改为 node_modules 中的内容
- javascript - React Spring:与 react-router 一起使用时 useTransition() 中的动态值
- python - Pandas:将各种类似的子字符串映射到单一的标准格式
- chart.js - 移动chartjs y轴说明
- python - 如何使用熊猫遍历excel文件中的多个标题?
- ios - 关于可本地化推送有效负载内容的一些问题