目录
什么是结构体?
结构是 C 编程中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。
#include "stdio.h"
main()
{
int a; //int是定义类型, a是定义变量
struct book a; //struct abc就类似为定义类型(先别管为什么这么写), a就是变量
}
结构体的组成
关于结构体大致三种不同不同的类型。
为了定义结构,您必须使用 struct 语句。
例:我想存书,包括书名title,作者author。
#include "stdio.h"
main()
{
struct book{ //book是自定义的结构体类名
char title[100];
char author[100];
};
struct book a[10]; //调用结构体,定义变量名a[10] ,也可以定义指针或其他的
}
若你认为每次调用结构体字好长,也可以直接在后面加入变量名。如下
#include "stdio.h"
main()
{
struct book{
char title[100];
char author[100];
}a[10]; //直接在后面添加变量名也是可以的
}
在简单点也可以不用结构体名,如下
#include "stdio.h"
main()
{
struct { //结构体的名也可以不定义
char title[100];
char author[100];
}a[10];
}
除此之外,我们也可使用一个typedef函数。
了解typedef函数
我们先了解一下这个函数,他是给已有的类型取一个新名字。关于他的用处如下。
#include "stdio.h"
main()
{
//在正常情况下
int a=10;
//使用typedef函数
typedef int abc;
abc a=10; //int类型赋予新的别名abc
}
所以我们在调用的时候,可以为结构体去个别名,在调用的时候就很简单了。
#include "stdio.h"
main()
{
struct book{
char title[100];
char author[100];
};
//使用typedef取个别名
typedef struct book abc;
abc a[10];
//或者直接结构体
typedef struct book{
char title[100];
char author[100];
} a[10];
}
关于typedef和指针的一些用法
//正常写一个指针
int a = 1;
int *p = &a;
//当typedef和指针用,如下:
typedef int *elp;
//那么可以变为
elp p = &a;
上述的elp就可以形象的理解为int *
typedef在数组中也有一些用法
//正常情况下,定义
int a[5];
//使用typedef
typedef int elp[5];
elp a;
//相当于int a[5];
typedef和结构体与指针的连用
当我们将typedef与结构体与指针揉一起,如下
typedef struct Node{
int x;
int y;
}*elp;
这与结构体指针又有一些不同,他与上述int的有些相同点,我们可以这样的将结构体理解为一种数据类型,运用如下:
typedef struct Node{
int x;
int y;
}*elp;
elp a;
//相当于
struct Node *a;