1.结构体的定义
“结构”是一种构造类型,它是由若干“成员”组成的。每一个成员可以是一个基本数据类型或者又是一个构造类型。
结构既然是一种“构造”而成的数据类型,那么在说明和使用之前必须先定义它,也就是构造它,如同在说明和调用函数之前要先定义函数一样。
2.结构体的声明
定义一个结构的一般形式:
struct 结构名
{成员列表};
成员列表由若干个成员组成,每个成员都是该结构的一个组成部分,对每个成员也必须做类型说明,形式为:
类型说明符成员名;
成员名的命名应符合标识符的书写规定;例如:
struct stu
{
Int num;
char *name;
char sex;
float score;
};
类型定义是一种声明,声明都是以“;”号结尾。
3.结构类型变量的说明
说明结构变量有以下三种方法:
1) 先定义结构,再说明结构变量。
格式:
struct stu
{
Int num;
char *name;
char sex;
float score;
};
例:
#include "stdafx.h"
struct Student
{
int num;
char * name;
};
int _tmain(int argc, _TCHAR* argv[])
{
struct Student stu;
stu.num=1001;
stu.name="李四";
printf("%d,%s\n",stu.num,stu.name);
struct Student stu2;
stu2.num=1002;
stu2.name="王五";
printf("%d,%s\n",stu2.num,stu2.name);
struct Student stu3;
stu3.num=1003;
stu3.name="赵六";
printf("%d,%s\n",stu3.num,stu3.name);
return 0;
}
2) 再定义结构类型的同时说明结构变量。
格式:
struct stu
{
Int num;
char *name;
char sex;
float score;
} boy1,boy2;
例:
#include "stdafx.h"
struct Student
{
int num;
char * name;
}stu,stu2,stu3;
int _tmain(int argc, _TCHAR* argv[])
{
struct Student stu;
stu.num=1001;
stu.name="李四";
printf("%d,%s\n",stu.num,stu.name);
struct Student stu2;
stu2.num=1002;
stu2.name="王五";
printf("%d,%s\n",stu2.num,stu2.name);
struct Student stu3;
stu3.num=1003;
stu3.name="赵六";
printf("%d,%s\n",stu3.num,stu3.name);
return 0;
}
3) 直接说明结构变量。
格式:
struct
{
Int num;
char *name;
char sex;
float score;
} boy1,boy2;
例:
#include "stdafx.h"
struct Student
{
int num;
char * name;
}stu,stu2,stu3;
int _tmain(int argc, _TCHAR* argv[])
{
stu.num=1001;
stu.name="李四";
printf("%d,%s\n",stu.num,stu.name);
stu2.num=1002;
stu2.name="王五";
printf("%d,%s\n",stu2.num,stu2.name);
stu3.num=1003;
stu3.name="赵六";
printf("%d,%s\n",stu3.num,stu3.name);
return 0;
}
4.结构变量的赋值
#include "stdafx.h"
struct stu{
int num;
char * name;
char sex;
float score;
}boy1,boy2;
int _tmain(int argc, _TCHAR* argv[])
{
boy1.num=102;
boy1.name="李四";
printf("input sex and score\n");
scanf("%c %f",&boy1.sex,&boy1.score);
boy2=boy1;
printf("Number=%d,\nName=%s\n",boy2.num,boy2.name);
printf("Sex=%c,\nScore=%f\n",boy2.sex,boy2.score);
return 0;
}
本程序中用赋值语句给num和name两个成员赋值,name是一个字符串指针变量。用scanf函数动态地输入 sex 和 score成员值,然后把 boy1 的所有成员的值整体赋予 boy2。最后分别输出boy2 的各个成员值。本例表示了结构变量的赋值、输入和输出的方法。
5结构变量的使用
#include "stdafx.h"
struct Student
{
int No;
char *Name;
void Show()
{
printf("我叫%s,学号是%d\n",Name,No);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
struct Student stu;
stu.No=1001;
stu.Name="李四";
stu.Show();
struct Student stu2;
stu2.No=1002;
stu2.Name="王五";
stu2.Show();
struct Student stu3;
stu3.No=1003;
stu3.Name="赵六";
stu3.Show();
return 0;
}