C数组的结构段错误

标签 c arrays pointers struct malloc

我正在尝试创建一个动态结构数组,并且我可以成功地向其中添加一个结构。但是我添加的任何更多结构都会导致段错误。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PEOPLE_BLOCK 4

struct Person {
    char *first_name;
    char *last_name;
    unsigned int age;
};

int add_person(struct Person **people, size_t *people_size, size_t *population, struct Person p) {

    if ((sizeof(struct Person) * *population) > *people_size) {
        return -1;
    }

    if ((sizeof(struct Person) * (*population + 1)) >= *people_size) {
        *people_size = *people_size + sizeof(struct Person) * PEOPLE_BLOCK;
        *people = realloc(*people, *people_size);
        if (!*people) {
            return -1;
        }
    }

    *people[*population] = p;
    ++*population;

    return 0;
}

int main(int argc, char const *argv[]) {

    size_t population;
    size_t people_size;
    struct Person *people, timn, batman;

    population = 0;
    people_size = sizeof(struct Person) * PEOPLE_BLOCK;
    people = malloc(people_size);

    timn.first_name = "Timn";
    timn.last_name = "Timothy";
    timn.age = 38;
    add_person(&people, &people_size, &population, timn);

    printf("Person 0's first name: %s\n", people[0].first_name);

    batman.first_name = "Bat";
    batman.last_name = "Man";
    batman.age = 42;
    add_person(&people, &people_size, &population, batman);

    printf("Person 1's first name: %s\n", people[1].first_name);

    free(people);

    return 0;
}

如果您能帮助我解释为什么会发生这种情况,我将不胜感激,谢谢!

最佳答案

问题在于这一行:

*people[*population] = p;

将其更改为:

(*people)[*population] = p;

为什么需要括号?

编译器有 rules of operator precedence .应用它们时,它会将您的代码视为:

*(people[*population]) = p;

这不是你想要的。给定一个指向指针的指针 Type **pp,

*pp[n] = value;

表示“获取从 pp 开始的第 n 指针,并将 value 分配到从指针所持有的地址取消引用的位置。换句话说,它本质上是这样的:

Type *p = pp[n];
*p = value;

真正想要的是这个:

Type *p = *pp;
p[n] = value;

这就是 (*pp)[n] 为您提供的,区分指针对指针的取消引用。否则,您将使用无效指针,从而导致您的错误。

关于C数组的结构段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29992107/

相关文章:

php - 将输入数组形成到 MySQL DB

c - C语言的机票预订系统

c - 如何获得与出现次数相对应的字母进行排序?

C中指针和整数的比较

c - C中的字符数组是否有最大返回长度

c - 整数常量的无符号类型

使用 Arduino IDE 创建 I2C 光传感器的回调函数

arrays - 在c中对动态数组进行排序

c - 如何从c(Ubuntu)中的文件中逐行读取?

ios - 将 NSArray 中的 TableView 项目分组到 Swift 中的 JSON 响应中返回