假设我有这样的指针结构:
typedef struct person {
char* name;
struct person* neighbor;
} person;
typedef struct jail {
struct person* first_inmate;
} jail;
我编写以下内容以在堆上分配这些结构,以便它们在局部范围之外持久存在:
void create_person(const char* person_name, person** person_ptr2ptr) {
if (!*person_ptr2ptr)
*person_ptr2ptr = (person*) malloc(sizeof(person));
(*person_ptr2ptr)->name = (char*)person_name;
(*person_ptr2ptr)->neighbor = NULL;
}
jail* create_jail(void) {
jail* _jail;
_jail = (jail*) malloc(sizeof(jail));
_jail->first_inmate = NULL;
return _jail;
}
为什么我不能插入'这些person
是这样的jail
吗?
void imprison(jail* jail_ptr, person* person_ptr) {
person* last_inmate = jail_ptr->first_inmate;
while (last_inmate != NULL)
last_inmate = last_inmate->neighbor;
last_inmate = person_ptr;
}
当我尝试访问san_jose_jail->first_inmate
或任何囚犯时,我会遇到段错误。名称:
int main(void) {
person* alice_ptr = NULL;
person* bob_ptr = NULL;
create_person("Alice", &alice_ptr);
create_person("Bob", &bob_ptr);
jail* san_jose_jail = create_jail();
imprison(san_jose_jail, alice_ptr);
imprison(san_jose_jail, bob_ptr);
// Why don't the pointers match?
printf("Alice is at %p\n", (void*)alice_ptr);
printf("First prisoner is at %p\n", (void*)san_jose_jail->first_inmate);
// Segfaults after next line
printf("Last prisoner's name is %s\n", san_jose_jail->first_inmate->neighbor->name);
free(san_jose_jail);
free(alice_ptr);
free(bob_ptr);
return 0;
}
我的目标是存储一个哈希表,其值是指向结构的指针,我能够插入/访问指针本身,但是当我在插入函数的范围之外访问指针时,指针会引用垃圾。我认为上面的例子抽象了问题并帮助我理解如何做到这一点。
答案 0 :(得分:1)
问题在于这句话:
last_inmate = person_ptr;
您正在修改neighbor
指针的本地副本,而不是结构中的指针未被触及。 imprison
方法应该是这样的:
void imprison(jail* jail_ptr, person* person_ptr) {
person** last_inmate = &jail_ptr->first_inmate;
while (*last_inmate != NULL)
last_inmate = &(*last_inmate)->neighbor;
*last_inmate = person_ptr;
}
答案 1 :(得分:0)
要将某人添加到jail中,juste会在列表的开头添加:
void imprison(jail* jail_ptr, person* person_ptr) {
person_ptr->neighbor = jail_ptr->first_inmate;
jail_ptr->first_inmate = person_ptr;
}