C - 基础 - 结构

结构的定义、初始化、访问和结构数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <string.h>

#define MAXTITL 41
#define MAXAUTL 31
#define MAXBOOK 10
// 结构定义
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
};

int main(int argc, char *argv[])
{
struct book crusoe; // 声明book类型变量
strcpy(crusoe.title, "鲁滨逊漂流记");
strcpy(crusoe.author, "迪福");
crusoe.value = 66.66;
printf("book crusoe,title: %s ,author: %s , value:%f \n", crusoe.title, crusoe.author, crusoe.value);
// 初始化结构
struct book stone= {
"红楼梦",
"雪里红芹菜",
100.00
};
printf("book stone,title: %s ,author: %s , value:%f \n", stone.title, stone.author, stone.value);
// 指定初始化项目
struct book piao = {
.author = "斯嘉丽",
.title = "乱世佳人",
.value = 22.22
};
printf("book piao,title: %s ,author: %s , value:%f \n", piao.title, piao.author, piao.value);
// 结构数组
struct book library[MAXBOOK];
library[0] = crusoe;
library[2] = stone;
library[3] = piao;
printf("sizeof struct book is %d , sizeof library is %d \n", sizeof(stone), sizeof(library));
return 0;
}

结构嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>

#define MAXTITL 41
// 结构定义
struct Author {
char name[30];
int age;
};

struct book {
char title[MAXTITL];
struct Author author;
float value;
};

int main(int argc, char *argv[])
{
struct Author author = {
"曹雪芹",
66
};
// 初始化结构
struct book stone = {
"红楼梦",
{"曹雪芹",66 }, // author
100.00
};
printf("book stone,title: %s ,author: %s,author'age: %d, value:%f \n", \
stone.title, stone.author.name, stone.author.age, stone.value);

return 0;
}

结构与指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>

#define MAXTITL 41
// 结构定义
struct Author {
char name[30];
int age;
};

struct book {
char title[MAXTITL];
struct Author author;
float value;
};

int main(int argc, char *argv[])
{
// 初始化结构数组
struct book library[2] = {
{
"红楼梦",
{ "曹雪芹",66 },
100.00
} ,
{
"西游记",
{ "吴承恩",88 },
101.00
} };
struct book *ptr = &library[0]; // 指向结构的指针

printf("book stone,title: %s ,author: %s,author'age: %d, value:%f \n", \
ptr->title, ptr->author.name, ptr->author.age, ptr->value);
ptr++; // 指向下一个
printf("book stone,title: %s ,author: %s,author'age: %d, value:%f \n", \
ptr->title, ptr->author.name, ptr->author.age, ptr->value);

return 0;
}

结构与函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>

struct swaper {
int a;
int b;
};
void swap(struct swaper *); // 参数为结构指针
void to_string(struct swaper pair); // 参数为结构

// 使用结构交换
int main(int argc, char *argv[])
{
struct swaper pair = {
1,2
};
to_string(pair);
swap(&pair);
to_string(pair);
return 0;
}

void swap(struct swaper * pair)
{
int temp = pair->a;
pair->a = pair->b;
pair->b = temp;
}

void to_string(struct swaper pair)
{
printf("swaper{a:%d,b:%d} \n", pair.a, pair.b);
}

推荐文章