为什么不让它变得更简单:与其尝试跟踪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
在该函数内部使用。
当然,如果你的整个“练习”都围绕着学习静态变量,这可能没有什么价值。但是我在这里所拥有的可能比在函数内部保留一个静态变量来进行数组索引更可取。