c - 传递指针结构

标签 c pointers struct

假设我有这样的指针结构:

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;
}

为什么我不能像这样将这些“插入” 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;
}

我的目标是存储一个哈希表,其值是指向结构的指针,我能够插入/访问指针本身,但当我在插入函数的范围之外访问它们时,指针会取消引用垃圾。我认为上面的例子抽象了问题并将帮助我理解如何做到这一点。

最佳答案

问题出在这个声明上:

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;
}

关于c - 传递指针结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34368102/

相关文章:

c - netinet/tcp.h 中的有效负载偏移值?

c - UART 接收中断在成功接收数小时后停止触发

c - 尝试访问结构数组成员时出现段错误

c - 固定数组的大小而不是在 C 中使用指针

c - Sleep() 函数在 C 中计时不正确

c - 我如何让 child 打印杀死它的信号?

c++ - 为什么 x[0] != x[0][0] != x[0][0][0]?

go - 从结构 slice 动态创建 map[string]struct 的常用函数

c++ - 避免在 C++ 中使用结构填充

c - 这是 C11 匿名结构吗?