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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
// struct union typedef . -> #include <stdio.h> #define MAXTITLE 41 #define MAXAUThOR 41 struct book { char title[MAXTITLE]; char author[MAXAUThOR]; float pirce; }; int main(int argc, char const *argv[]) { /* 可以在函数内部定义 可以省略标记book 可以直接在定义之后跟变量名library struct book { char title[MAXTITLE]; char author[MAXAUThOR]; float pirce; } library; */ struct book library; /* 可以初始化 struct book library = { "彼岸花", "安妮宝贝", 1.01 }; 可以部分初始化 struct book library = { .price = 1.01 }; 可以乱序初始化 struct book library = { .price = 1.01, .title = "彼岸花", .author = "安妮宝贝" }; 复合文字写法,复合文字也可以用作函数参数 struct book library = (struct book){ "彼岸花", "安妮宝贝", 1.01 }; */ /* 可以嵌套结构 struct names { char first[LEN]; char last[LEN]; }; struct guy { struct name handle; char favfood[LEN]; char job[LEN]; float income; }; */ puts("Enter the book title"); gets(library.title); puts("Enter the book author"); gets(library.author); puts("Enter the book pirce"); scanf("%f", &library.pirce); printf("title:%s author:%s pirce:%.2f\n", library.title, library.author, library.pirce); return 0; } // 指向结构体的指针 #include <stdio.h> #define LEN 20 struct names { char first[LEN]; char last[LEN]; }; struct guy { struct names handle; char favfood[LEN]; char job[LEN]; float income; }; int main(int argc, char const *argv[]) { struct guy fellow[2] = { { {"Ewen", "Villard"}, "grilled salmon", "personality coach", 58112.00 }, { {"Rodney", "Swillbelly"}, "tripe", "tabloid editor", 232400.00 } }; // 声明guy类型的指针 struct guy * him; printf("address #1:%p #2:%p\n", &fellow[0], &fellow[1]); him = &fellow[0]; printf("pointer #1:%p #2:%p\n", him, him + 1); // 指针->成员名 结构名.成员名 (*him).income必须用(),因为.的优先级比*高 printf("him->income is $%.2f:(*him).income is $%.2f\n", him->income, (*him).income); him++; printf("him->favfood is %s:him->handle.last is %s\n", him->favfood, him->handle.last); return 0; } // 向函数传递结构信息 #include <stdio.h> struct test { double a; double b; char c; int d; }; double sum1(double, double); double sum2(const struct test *); double sum3(struct test); int main(int argc, char const *argv[]) { struct test test1 = { 3.14,3.15,'a',10 }; // 向函数传递结构成员 printf("%.2f\n", sum1(test1.a, test1.b)); // 向函数传递结构指针,需要&(跟数组不同) printf("%.2f\n", sum2(&test1)); // 对于支持结构体作为函数参数的编译器,也可以这么写 printf("%.2f\n", sum3(test1)); return 0; } double sum1(double a, double b) { return a + b; } double sum2(const struct test * test1) { return test1->a + test1->b; } double sum3(struct test test1) { return test1.a + test1.b; } |