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