C 语言结构体定义方法
为了避免遗忘,下面记录了几种常见的 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 43 44
| #include <stdio.h>
struct Book{ int id; char* name; double price; char* auth; };
int main() { struct Book b1={ 1, "Book 1", 111.11, "Author 1" }; struct Book b2; b2.id=2; b2.name="Book 2"; b2.price=222.22; b2.auth="Author 2"; struct Book b3={ .id=3, .price=333.33, .name="Book 3", .auth="Author 3" }; struct Book b4={ id: 4, price: 444.44, name: "Book 4", auth: "Author 4" }; return 0; }
|
结构体数组初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| struct Book b[10]={ [0]={ .id=0, .price=123, .name="Book 0" }, [5]={ id: 5, price: 555.55 }, [6]={ .auth="Author 6" } };
|
参考资料:
- C语言结构体之顺序初始化和乱序初始化 https://blog.csdn.net/zhaodong1102/article/details/122883306