结构体数组和结构体的嵌套
结构体数组
复制代码
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77#include <stdio.h> #include <string.h> struct Student { int age; char name[50]; int score; }; int main(int argc, char const *argv[]) { //结构体数组的初始化 struct Student a[5] = { {18, "mike", 59}, {19, "jiang", 66}, {33, "xiaobai", 82}, {28, "lily", 77}, {30, "xiaoan", 80} }; int n = sizeof(a)/sizeof(a[0]); int sum = 0; for (int i = 0; i < n; ++i) { sum += a[i].score } printf("平均分:%dn", sum/n); return 0; } int main01(int argc, char const *argv[]) { struct Student a[5];//结构体数组 //操作元素 a[0].age = 18; strcpy(a[0].name, "mike"); a[0].score = 59; //操作某个元素地址 (a+1)->age = 19; strcpy((a+1)->name, "jiang"); (a+1)->score = 60; //操作元素 ( *(a+2) ).age = 20; strcpy(( *(a+2)).name, "lily"); ( *(a+2)).score = 61; //用指针访问 struct Student *p = a; p = &a[0]; p[3].age = 21; strcpy(p[3].name, "xiaoming"); p[3].score = 62; (p+4)->age = 22; strcpy((p+4)->name, "xiaojiang"); (p+4)->score = 88; int i = 0; int n = sizeof(a)/sizeof(a[0]); for(i = 0; i < n; i++) { printf("%d, %s, %dn", a[i].age, a[i].name. a[i].score); } 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#include <stdio.h> #include <string.h> struct Info { int age; char name[50]; } struct Student { struct Info info; int score; }; int main(int argc, char const *argv[]) { struct Student s; s.info.age = 18; strcpy(s.info.name, "mike"); s.score = 59; struct Student *p = &s; p->info.age = 18; strcpy(p->info.name, "mike"); p->score = 59; struct Student tmp = {18, "mike", 59}; printf("%d, %s, %dn", tmp.info.age, tmp.info.name, tmp.score); return 0; }
最后
以上就是超级便当最近收集整理的关于结构体数组和结构体的嵌套的全部内容,更多相关结构体数组和结构体内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复