执行结果 :
octopus@octopus-Vostro-270s:~/code/c/struct$ gcc array_struct.c
octopus@octopus-Vostro-270s:~/code/c/struct$ ./a.out
team1 : team1[i].name = Tom, team1[i].age = 12
team1 : team1[i].name = Jack, team1[i].age = 13
team2 : team2[i].name = CJ, team2[i].age = 34
team2 : team2[i].name = KI, team2[i].age = 32
(2) 结构体数组示例程序
需求 : 实现一个统计 C 语言关键字出现次数;
代码 :
#include<STDIO.H>
#include<CTYPE.H>
#include<STRING.H>
#define MAXWORD 10
/*
* 定义结构体类型 key
* 该类型结构体中存储一个 字符串(关键字) 和 int 数据(关键字出现次数)
* 同时声明一个结构体数组
* 对结构体数组进行初始化
*
*
*/
struct key
{
char *word;
int count;
}key_count[] =
{
auto, 0,
break, 0,
case, 0,
char, 0,
const, 0,
continue, 0,
default, 0,
void, 0,
volatitle, 0,
while, 0
};
int main(int argc, char **argv)
{
int n;
char word[MAXWORD];
/*循环接收字符串, 如果字符串与结构体数组中匹配, 结构体的count ++*/
while(getword(word, MAXWORD) != EOF)
if(isalpha(word[0]))
if((n = binsearch(word, key_count, 10)) >= 0)
key_count[n].count++;
/*打印大于0的关键字及个数*/
for (n = 0; n < 10; n ++)
if(key_count[n].count > 0)
printf(%2d %s
, key_count[n].count, key_count[n].word);
return 0;
}
/*
* 重要api解析 :
* int getc(FILE *stream)从标准输入流中读取字符
* int ungetc(int c, FILE *stream)将字符退回到标准输入流中
* int isspace(int c) 判断字符是否是空格 ' ' '
' '
' ' ' ' '
* int isalpha(int c) 判断是否是字母
*/
int getword(char *word, int lim)
{
int c, getc(FILE*), ungetc(int, FILE*);
char *wp = word;
/*过滤空格,如果输入的不是空, 就继续向下执行*/
while(isspace(c = getc(stdin)));
/*如果输入的不是结束符,那么 wp指针,先取值, 之后地址自增*/
if(c != EOF)
*wp++ = c;
/*如果输入的不是字母, 直接返回, 关键字里面没有数字开头的*/
if(!isalpha(c))
{
*wp = '';
return c;
}
/*