C语言中数组允许可存储相同类型数据项的变量,结构是C编程中另一种用户自定义的可用的数据类型,它允许存储不同的数据项。
结构体中可的数据成员可以是基本数据类型,如 int , float , char 等,也可以是其他结构体类型,指针类型等。 个人认为可以理解为 JAVA中的对象。
定义结构
由 关键词 struct 和 结构体名 组成
例如:
struct tag {
member-list
member-list
member-list
...
} variable-list ;
其中
- tag 是结构体标签
- member-list是标准的变量定义, 比如 int i;或者 float f;或其他
- variable—list 结构变量,定义在结构的末尾,最后一个分号之前,可以指定一个或多个结构变量。
以 BOOK 结构为例子
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
- 一般情况, tag 、member-list 、 variable-list , 至少要出现两个。
- 两个结构体互相包含,需要其中一个进行不完整声明
- 访问成员变量使用成员访问运算符(.)
下面直接运用一个方法进行测试。
int struct_demo()
{
//先测试一下声明的方式
// 声明结构体变量,没有标明标签
struct
{
int a;
char b;
double c;
} s1;
//标签命名为 SIMPLE ,没有声明变量
struct SIMPLE
{
int a;
char b;
double c;
};
//使用标签,声明了变量 ,没有成员
struct SIMPLE t1,t2[20],*t3;
//也可以用 typedef 创建新类型
typedef struct
{
int a;
char b;
double c;
} Simple2;
//声明之后可以使用 Simple2 作为类型声明新的结构体变量
Simple2 u1, u2[20], * u3;
//声明一个包含了其他结构体的结构体
struct COMPLEX
{
char string[100];
struct SIMPLE a;
};
//声明一个包含指向自己类型指针的结构体
struct NODE
{
char string[100];
struct NODE* next_node;
};
//声明两个结构体互相包含,需要对其中一个结构体进行不完整声明
struct B;
struct A
{
struct B* partner;
int a;
};
struct B
{
struct A* partner;
int b;
};
//初始化
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_int;
}book = { "C语言","RUNOOB","编程语言",123456 };
struct Books book1;
strcpy(book1.title, "B语言");
strcpy(book1.author, "RUUJK");
strcpy(book1.subject, "编程语言");
book1.book_int = 123123;
printf("输出测试:\n");
printf("book title : %s \n", book.title);
printf("book author : %s \n", book.author);
printf("book subject : %s \n", book.subject);
printf("book book_id : %d \n", book.book_int);
printf("book 1 title : %s \n", book1.title);
printf("book 1 author : %s \n", book1.author);
printf("book 1 subject : %s \n", book1.subject);
printf("book 1 book_id : %d \n", book1.book_int);
也可将结构体当作参数传递给函数,void printBook( struct Books book){ printf("book title: %s \n ", book.title); ......}
当然也可以定义一个指针,指向结构体的指针: struct Books *struct_poinrer;。在调用成员变量时使用 运算符 “->” 。 printf("book title: %s \n ", book->title);
结构体大小计算
struct Person {
char name[20];
int age;
float height;
};
int main() {
struct Person person;
printf("结构体 Person 大小为: %zu 字节\n", sizeof(person));
return 0;
}