为什么不让它变得更简单:与其尝试跟踪insert 函数中的索引,不如在main 函数中找到索引。因此:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array */
#define HOW_MANY 7
#define MAXSTRLEN 32
/* declare your struct for a person here */
struct person
{
char name [MAXSTRLEN];
int age;
};
static void insert (struct person *people, char *name, int age)
{
strncpy(people->name, name, MAXSTRLEN);
people->age = age;
}
int main(int argc, char **argv) {
// Move arrays here; if they are global instead,
// there would be need to pass name and age to insert()
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
/* declare the people array here */
struct person people[12];
int i;
for (i =0; i < HOW_MANY; i++)
{
insert (&people[i], names[i], ages[i]);
}
/* print the people array here*/
for (i =0; i < HOW_MANY; i++)
{
printf("%s\n", people[i].name);
printf("%d\n", people[i].age);
}
return 0;
}
people->name 语法是(*people).name 的简写。也就是说,您取消引用指针以获取实际结构(*people),然后访问结构编号;由于运算符优先规则,您需要在*people 周围加上括号。
我不确定您对指针有多熟悉,但在 C 中,这很常见(将指向结构的指针传递给函数,然后在该函数中使用 structure->member。
当然,如果您的整个“练习”都围绕着学习静态变量,那么这可能没有什么价值。但是我在这里所拥有的可能比在函数内部保留一个静态变量来进行数组索引更可取。