【转】0长度数组的妙用
【转】http://blog.chinaunix.net/uid-20196318-id-28810.html
1.前言
零长度是指定义数组时,指定其长度为0(如int arr[0];),这样的数组不占用实际的空间,但能通过数组名访问到其指向的地址。
2.代码实例
1 #include <stdlib.h> 2 #include <stdio.h> 3 struct device 4 { 5 int num; 6 int count; 7 int reserve[0]; 8 /* 9 * reserve是一个数组名;该数组没有元素;该数组的其实地址紧随结构体device之 10 * 后;这种声明方法可以巧妙的实现C语言里的数组扩展,比将reverse定义为指针, 11 * 再为指针分配空间的做法要简单一些,并且可以节省一个指针的存储空间 12 */ 13 }; 14 15 16 int main() 17 { 18 struct device * p_dev = 19 (struct device *) malloc (sizeof(struct device) + sizeof(int)*25); 20 //sizeof(int)*25是数组reserve的具体空间(25个元素) 21 22 p_dev->reserve[0] = 100; 23 p_dev->reserve[24] = 0; 24 25 printf("p_dev->reserve[0] = %d\n", p_dev->reserve[0]); 26 printf("p_dev->reserve[24] = %d\n", p_dev->reserve[24]); 27 printf("sizeof(struct device) = %d\n",sizeof(struct device)); 28 29 //将结构体device之后的第一个内容(int值,其实就是reserve[0]的值) 赋值给a 30 31 32 int a = *(&p_dev->count + 1); 33 printf("a = %d\n", a); 34 return 0;
运行结果:
p_dev->reserve[0] = 100
p_dev->reserve[24] = 0
sizeof(struct device) = 8
a = 100
内存布局:
|
num |
count |
reverse[0] |
… |
… |
… |
reverse[24] |
|<--------struct device-------->|

浙公网安备 33010602011771号