结构体作为一种自定义数据类型,结构类似于数组,但是结构体名与数组名有很大的区别:数组名是作为内存中固定不可修改的地址常量而存在,而结构体相当于int,double之类的系统内定类型,代表了一段内存空间的内容。
1 #include <stdio.h> 2 struct student 3 { 4 char old; 5 char sex; 6 }; 7 8 int main() 9 { 10 struct student li = { 11 16, 12 5 13 }; 14 printf("%x\n",li); 15 printf("%d\n",*(int *)&li); 16 return 0; 17 }
ubuntu@ubuntu:~/code/2017.8.31$ ./test2 510 1271399696
如图上代码,讲结构体类型以16进制输出结果为510,相当于将两个char型数据16和5组合成一个int型数据 ,因为16在低地址,5在高地址根据小端对齐规则,应该5在int型高位,16在int型低位,所以输出结果为510。
与int等普通类型相同,如果对结构体变量取地址&,也可以得到结构体的首地址。
相同的,两个同类型结构体,可以执行简单赋值,即执行浅拷贝。在下图的代码中,两个相同类型结构体变量赋值之后,其成员.name分别指向相同字符串地址,进行简单的内容复制操作。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 struct student 5 { 6 char *name; 7 int old; 8 }; 9 int main() 10 { 11 struct student n1; 12 13 n1.name = (char *) malloc(16); 14 strcpy(n1.name,"helloworld"); 15 n1.old = 16; 16 17 18 struct student n2; 19 n2 = n1; 20 printf("%p\n","xiaoming"); 21 printf("%p\n",n1.name); 22 printf("%p\n",n2.name); 23 }
1 ubuntu@ubuntu:~/code/2017.8.31$ ./test3 2 0x400684 3 0x21e9010 4 0x21e9010
而对于一个结构体类型的初始化,也可以像普通变量int型等一样,用已经定义的同类型结构体进行对其进行初始化。如struct student a ;struct student b = a;
同时也支持像数组一样用 {}和成员进行初始化。如:
struct student n1 = { .name = "xiaoming", .old = 10 }
同时,如果结构体中包含一个char型数组,在{}中如上图用字符串初始化成员,会将字符串中内容拷贝到数组中,如果结构体中包含一个char型指针,如上图初始化,成员会指向常量字符串“xiaoming”的地址。