需要帮助打印结构体指针数组 我哪里出错了?请帮忙
include <stdio.h>
include <stdlib.h>
define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
struct person
{
char *name;
int age;
};
static void insert (struct person *people[], char *name, int age) {
static int nextfreeplace = 0;
typedef struct person newperson;
newperson *structperson = (newperson*)malloc(sizeof(newperson));
(*structperson).name= name;
(*structperson).age = age;
printf("%s",(*structperson).name);
people[nextfreeplace] = &structperson;
printf("%s",(*people[nextfreeplace]).name);
nextfreeplace++;
}
int main(int argc, char **argv) {
struct person *people[HOW_MANY];
for (int c=0; c < HOW_MANY;c++) {
insert (people, names[c], ages[c]);
}
print the people array here
for (int i=0; i < HOW_MANY;i++) {
printf("%s \n",&(*people[i]).name);
}
return 0;
}
最佳答案
在进行 malloc 时,您将 structperson 声明为值而不是指针。然后您尝试从那时起将其作为指针引用(即用星号取消引用它)。
Here is how I would write it 。我做了一些更改,例如删除静态变量(您应该处理分配它的数组,您的函数不应该存储数组的状态,然后没有其他人可以使用它)。
关于c - 帮助使用 c 中的指针、结构体和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4025627/