C语言结构体
-
结构变量的初始化
#include<stdio.h> typedef struct Node { int a; int b; }node; void printNode(node ele); int main() { node node1 = {1, 2}; node array[2] = {{3, 4}, {5, 6}}; printNode(node1); printNode(array[0]); printNode(array[1]); return 0; } void printNode(node ele) { printf("%d %d\n", ele.a, ele.b); }
运行结果:
1 2
3 4
5 6 -
相同类型的结构体可以整体赋值(这里是值的传递,而不是地址的传递)
#include<stdio.h> typedef struct Node { int a; int b; }node; int main() { node node1, node2; node1.a = 1; node1.b = 2; node2 = node1; printf("%d %d\n", node2.a, node2.b); printf("%x %x\n", &node1, &node2); return 0; }
运行结果:
1 2
62fe10 62fe00 -
结构体中的成员地址会按类型自动对齐。因此,成员的地址不一定是连续的。
#include<stdio.h> typedef struct Node { char a; char b; int c; }node; int main() { printf("offset of a is %x\n", &(((node*)0)->a)); printf("offset of b is %x\n", &(((node*)0)->b)); printf("offset of c is %x\n", &(((node*)0)->c)); return 0; }
运行结果:
offset of a is 0
offset of b is 1
offset of c is 4