声明一个结构体类型:
struct 结构体名
{成员表列};
定义结构体变量的方法:
(1)先声明结构体类型再定义变量名。 在定义了结构体变量后,系统会为之分配内存单元.
例如:struct student student1,student2;
(2)在声明类型的同时定义变量,例如:
struct 结构体名
{
成员表列
}变量名表列;
3) 直接定义结构体类型变量,例如:
struct
{
成员表列
}变量名表列;
即不出现结构体名。
结构体变量的引用:
(1)不能将一个结构体变量作为一个整体进行输入和输出。引用结构体变量中成员的方式为:
结构体变量名.成员名
(2) 如果成员本身又属一个结构体类型,则要用若干个成员运算符,一级一级地找到最低的一级的成员。只能对最低级的成员进行赋值或存取以及运算。
(3) 对结构体变量的成员可以像普通变量一样进行各种运算(根据其类型决定可以进行的运算).
(4) 可以引用结构体变量成员的地址,也可以引用结构体变量的地址。结构体变量的地址主要用作函数参数,传递结构体变量的地址。
结构体变量初始化:
struct student {
long int num;
char name[20];
char sex;
char addr[20];
}a={10101, "LiLin", 'M′, "123 Beijing Road″ };
定义结构体数组:
struct student
{
int num;
char name[20];
char sex;
int age;
float score;
char addr[30];
};struct student[3];
或者直接定义一个结构体数组
struct
{int num;
…};stu[3];
结构体数组初始化:
struct student
{int num;
...
};
struct student str[ ] { {…},{...},{...}};
或者:
struct student
{int num;char name[20]; char sex;
int age; float score; char addr[30];
}; stu[2]={ { 10101, "LiLin", 'M', 18, 87.5, "103 BeijingRoad" }, {10102, "Zhang Fun", 'M', 19, 99, "130 Shanghai Road" } };
一个结构体变量的指针就是该变量所占据的内存段的起始地址。可以定义一个指针变量,用来指向一个结构体变量,此时该指针变量的值是结构体变量的起始地址。指针变量也可以用来指向结构体数组中的元素.
以下3种形式等价:
① 结构体变量.成员名
②(*p).成员名
p->成员名
“->”称为指向运算符
“.”称为成员运算符
应用:
#include <stdio.h>
#define N 3
struct student
{
char num[6];
char name[20];
int score[3];
};
//struct student stu[5];
void input(struct student *p,int n)
{
int i,j;
for(i=0;i<n;i++,p++)
{
printf("第%d个学生的信息:\n",i+1);
printf("请输入学号:");
scanf("%s",(*p).num);
printf("请输入姓名:");
scanf("%s",(*p).name);
for(j=0;j<3;j++)
{
printf("请输入分数%d:",j+1);
scanf("%d",(*p).score+j);
}
printf("\n");
}
}
void print(struct student *p,int n)
{
int i,j;
for(i=0;i<n;i++,p++)
{
printf("第%d个学生的信息\n",i+1);
printf("学号: %s ",(*p).num);
printf("姓名: %s ",(*p).name);
printf("分数:");
for(j=0;j<3;j++)
{
printf("%d ",(*p).score[j]);
}
printf("\n");
}
}
void main()
{
struct student *p;
struct student stu[N];
p = stu;
input(p,N);
print(p,N);
}