编译错误:请求不是结构或联合错误

在这个程序中,我试图创建一个结构,然后初始化一个具有该结构类型的数组,将名称和年龄放入数组中,并打印出结果。 但是,当我编译文件时,它说“名字”和“年龄”不是结构或联合。有人可以发现我的错误。谢谢你

#include  #include  /* these arrays are just used to give the parameters to 'insert', to create the 'people' array */ char *names[7]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim", "Harriet"}; int ages[7]= {22, 24, 106, 6, 18, 32, 24}; /* declare your struct for a person here */ typedef struct{ char *names; int ages; } person; static void insert (person **p, char *s, int n) { *p = malloc(sizeof(person)); static int nextfreeplace = 0; /* put name and age into the next free place in the array parameter here */ (*p)->names=s; (*p)->ages=n; /* modify nextfreeplace here */ nextfreeplace++; } int main(int argc, char **argv) { /* declare the people array here */ person *p[7]; //insert the members and age into the unusage array. for (int i=0; i < 7; i++) { insert (&p[i], names[i], ages[i]); p[i]= p[i+1]; } /* print the people array here*/ for (int i=0; i < 7; i++) { printf("name: %s, age:%i\n", p[i].names, p[i].ages); } } 

你将p声明为指向结构的指针数组。 在printf行上,你用p[i]取消引用p ,但是p仍然是指向结构的指针,你想用->访问它的字段

 for (int i=0; i < 7; i++) { printf("name: %s, age:%i\n", p[i]->names, p[i]->ages); } 

当你在for循环中递增i时,你不需要移动你的p [i]指针,删除, p[i] = p[i + 1]

 for (int i=0; i < 7; i++) { insert (&p[i], names[i], ages[i]); } 

person *p[7]声明一个由七个指针组成的数组,因此p[i]是指向结构的指针。 因此,您需要取消引用此指针以访问其成员。

 printf("name: %s, age:%i\n", (*p[i]).names, (*p[i]).ages); 

要提高可读性,可以使用后缀运算符->

 printf("name: %s, age:%i\n", p[i]->names, p[i]->ages); 

C11(1570),第6.5.2.3节结构和工会成员
后缀表达式后跟->运算符和标识符指定结构或联合对象的成员。 该值是第一个表达式指向的对象的指定成员的值,并且是左值。如果第一个表达式是指向限定类型​​的指针,则结果具有指定成员类型的限定版本。