定义结构体:
(1)先定义结构体类型,再定义结构体变量(推荐使用!)
struct student
{
long number;
char name[20];
char sex;
int age;
float score[3];
};
定义结构体类型变量:
示例
struct student stu1,stu2;
(2)定义结构体类型同时定义结构体类型变量
struct student
{
long number;
char name[20];
char sex;
int age;
float score[3];
}stu1,stu2;
也可以再定义如下变量:
示例
struct student stu3,stu4;
(3)直接定义结构体类型变量
struct
{
long number;
char name[20];
char sex;
int age;
float score[3];
}stu1,stu2;
注意:
该方法无法记录该结构体类型,所以除直接定义外,不能再定义该结构体类型变量。
typedef+struct+指针
(1)typedef
作用:为一种数据类型定义一个新的别名。合理的数据类型包括基本数据类型(int,char等)和自定义的数据类型(struct等)。
typedef的语法:
#typedef 原类型名 新类型名
# 存在类型 别名
typedef int interger;
int x,y; <=> interger x,y; #两者等价
(2)typedef+struct 结合使用
typedef struct tagMyStruct
{ int num;
long length;
}MyStruct;
例子
struct node
{
int data;
char sex;
}S1,S2;
typedef struct node SS;
#等价于
typedef struct node
{
int data;
char sex;
}SS;
#类型名
(3)typdef+struct+指针 结合使用
typedef struct node
{ int data;
struct node *next;#先使用是允许的
}*pointer;
等价于
typedef struct node *pointer;#也是允许的
struct node
{ int data;
pointer next;
};
等价于
struct node
{ int data;
struct node *next;
};
typedef struct node *pointer;
# 结构体指针类型:指向结构体类型的类型
#最后一种是最规范的写法
结构体变量的引用:
(1)结构体变量名.成员名
#例子
printf("%d", S1.age);
(2)指向结构体的指针变量名->成员名
#例子
pointer p;#pointer本身就是一个指针类型,通过它定义的p也是指针类型
printf("%d", *p.data); 不建议
#<=>
printf("%d", p->data);