结构体数组,以及结构体的基本操作
/*************************************************************************
> File Name: excise.c
> Author: XXDK
> Email: v.manstein@qq.com
> Created Time: Mon 06 Mar 2017 03:01:38 AM PST
************************************************************************/
#include<stdio.h>
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
struct commander {
char name[24]; // 姓名
int age; // 年龄
int wisdom; // 智力
};
void input_cmd_info(struct commander *cmdp, int size);
void output_cmd_info(struct commander *cmdp, int size);
void sort_wisdom(struct commander *cmdp, int size);
int main()
{
// 结构体数组
struct commander cmd[5];
input_cmd_info(cmd, ARRAY_SIZE(cmd));
output_cmd_info(cmd, ARRAY_SIZE(cmd));
sort_wisdom(cmd, ARRAY_SIZE(cmd));
output_cmd_info(cmd, ARRAY_SIZE(cmd));
return 0;
}
void input_cmd_info(struct commander *cmdp, int size)
{
printf("please input 5 commander informationi<name age wisdom>: \n");
for(int i = 0; i < size; i++, cmdp++) {
printf("input: ");
scanf("%s%d%d", cmdp->name, &cmdp->age, &cmdp->wisdom);
}
}
void output_cmd_info(struct commander *cmdp, int size)
{
printf("All commander information is:\n");
for(int i = 0; i < size; i++) {
printf("commander %d name: %s\n", i, cmdp[i].name);
printf("commander %d age: %d\n", i, cmdp[i].age);
printf("commander %d wisdom: %d\n", i, cmdp[i].wisdom);
printf("---------------------------\n");
}
}
//按照智商排序
void sort_wisdom(struct commander *cmdp, int size)
{
struct commander temp;
int flag = 0, i, j;
//bubble sort
for(i = 0; i < size - 1; i++) {
for(j = 0, flag = 0; j < size - 1 - i; j++) {
if(cmdp[j].wisdom < cmdp[j + 1].wisdom) {
temp = cmdp[j];
cmdp[j] = cmdp[j + 1];
cmdp[j + 1] = temp;
flag = 1;
}
}
if(!flag) {
break;
}
}
}