C语言-结构


结构

感觉跟其它语言的类拥有很多属性一样

定义

参考

1

1
2
3
4
5
6
7
8
#include <stdio.h>
#define MAXTITLE 12
#define AUTHOR 12
struct book{
char title[maxtitle];
char author[author];
float value;
};
1
struct book b1, b2;

2

1
2
3
4
5
6
//定义结构体,同时声明声明变量
struct book{
char title[maxtitle];
char author[author];
float value;
} b1, b2;
1
2
//此后还可以
struct book b3;

3

1
2
3
4
5
6
7
/**一般不使用这种方法,因为直接定义结构体变量b1、b2之后,就不能再继续定义该类型的变量
*/
struct {
char title[maxtitle];
char author[author];
float value;
} b1, b2;

4

1
2
3
4
5
6
7
typedef struct{
char title[maxtitle];
char author[author];
float value;
} student;

// 声明只能用student

5

1
2
3
4
5
6
7
typedef struct student{
char title[maxtitle];
char author[author];
float value;
} student_t;

// 声明可以用struct student或student_t

声明

1
2
3
struct book library; //声明单个
struct book library1library2; //声明多个
struct book * ptbook;// 声明一个指针指向该结构

定义和声明放一起

1
2
3
4
5
struct book{
char title[maxtitle];
char author[author];
float value;
} library; //这时省略book标记也可以

初始化

可以和初始化数组类似的方法初始化

注意初始化的每一条项目必须与成员类型相同;赋值顺序要和定义的一样

1
2
3
4
5
6
1.
struct book library = {
"the pirate and the deious damsel",
"renee vivote",
1.95
};
1
2
2.
gets(library.title); //将输入的值赋给title

访问结构成员

1
2
// 结构变量.成员名称
library.title;

结构的指定初始化项目

跟数组的初始化项目类似

赋值顺序不一定要和定义的一样

1
2
3
4
5
struct book library = {
.title = "fxxx",
.value = 12.5,
.author = "xxx"
};

嵌套结构

C语言-嵌套结构

本文标题:C语言-结构

文章作者:TTYONG

发布时间:2020年08月27日 - 22:08

最后更新:2022年09月22日 - 19:09

原始链接:http://tianyong.fun/C%E8%AF%AD%E8%A8%80-%E7%BB%93%E6%9E%84.html

许可协议: 转载请保留原文链接及作者。

多少都是爱
0%