结构体
1.声明一个结构体
struct 自定义结构体类型名 结构体变量名
同时必须声明结构体内部的所有成员类型
例如声明一个学生的成绩单
struct Student Score
{
char aName[128];
int iAge;
int iNum;
int iScore;
};
这是一个结构体的声明,其中包括了姓名,年龄,学号,分数。使用这种方法可以在主函数中声明自己需要的结构体
例如:struct Student Score; 当然可以声明结构体数组例如struct Student Score[3];
进一步的我们可以使用typedef关键字使得我们声明起来更方便
typedef struct student
{
char aName[128];
int iAge;
int iNum;
int iScore;
}STU;//建议这里大写,不知道为什么如果用小写总是容易出错//
这样声明后就可以方便的使用STU来声明了。
例如
STU Score[3];和用struct 声明是一样的。
结构体的大小:
结构体的大小是声明结构体内所有成员大小的总和
例如上边的结构体(X86_64系统)
sizeof(Score)=128+4+4+4=140字节
初始化及访问结构体内部的元素:
初始化使用"."运算符
例如初始化一个成绩: Score.iScore=95;
特别的对于这种名字为字符串的赋值时,建议使用字符串复制函数strcpy()函数来初始化。
strcpy(Score.iScore,"zhang san");
下面是一个完整的程序:
使用结构体记录三个学生的成绩,姓名,年龄,学号,返回成绩最大的成绩和学号。
#include<stdio.h>
#include<string.h>
#define SUCCESS 1
#define FAILL (-1)
#define std STD
typedef struct Student
{
int Scoure;
int iNumber;
char cName[128];
int iAge;
} std;/*使用typedef后自定义名称建议大写*/
int find_high_score(std *ptr,const unsigned int iLen,int *Max,int *MaxN);
int main()
{
std student[3];
int Max;
int MaxN;
int iRet;
memset(student,0,sizeof(student));
student[0].Scoure =80;
student[0].iNumber =23;
student[0].iAge =17;
strcpy(student[0].cName ,"zhang san");
student[1].Scoure =92;
student[1].iNumber =24;
student[1].iAge =17;
strcpy(student[0].cName ,"wang er");
student[2].Scoure =85;
student[2].iNumber =25;
student[2].iAge =17;
strcpy(student[0].cName ,"li si");
iRet = find_high_score(student,sizeof(student)/sizeof(std), &Max, &MaxN);
if(iRet!=SUCCESS)
{
return iRet;
}
printf("The hinghest score is %d\n",Max);
printf("The student Number is %d\n",MaxN);
return SUCCESS;
}
int find_high_score(std *ptr,const unsigned int iLen,int *Max,int *MaxN)/*传递进参数后使用ptr*/
{
int iMaxs;
int iMaxn;
int i;
if(NULL== ptr || NULL==Max || NULL==MaxN)/*注意==与=的使用*/
{
return FAILL;
}
if(0==iLen)
{
return FAILL;
}
iMaxs=ptr->Scoure;
iMaxn=ptr->iNumber;
for(i=0;i<iLen;i++)
{
if(iMaxs<ptr->Scoure)
{
iMaxs=ptr->Scoure;
iMaxn=ptr->iNumber;
}
ptr++;
}
*Max=iMaxs;/*不能改变传递进来的指针的值,可以改变指针指向的值*/
*MaxN=iMaxn;
return SUCCESS;
}