首页 > 解决方案 > 指针丢失引用的问题

问题描述

我正在尝试做一棵孩子和父亲的树,但是当孩子出生在一个函数中时,我失去了对孩子的提及,这里将举一个狗的例子:

#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

你会看到第一个输出顺利,但另一个丢失了参考,我不知道如何解决它

标签: cpointersreferencetree

解决方案


Dog pancho;have_children()函数中的局部变量。当函数返回时,该内存被释放。您保存了一个指向不再有效的内存的指针。此行为未定义。


推荐阅读