Chinaunix首页 | 论坛 | 博客
  • 博客访问: 383955
  • 博文数量: 69
  • 博客积分: 1992
  • 博客等级: 上尉
  • 技术积分: 1162
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-03 19:50
文章分类
文章存档

2015年(1)

2011年(55)

2010年(13)

分类: C/C++

2011-04-24 16:02:08

转自:http://blog.chinaunix.net/space.php?uid=20196318&do=blog&id=28810


零长度是指定义数组时,指定其长度为0(如int arr[0];),这样的数组不占用实际的空间,但能通过数组名访问到其指向的地址。如下例所示:

#include <stdlib.h>
#include <stdio.h>
struct device
{
    int num;
    int count;
    int reserve[0]; 
/* 
* reserve是一个数组名;该数组没有元素;该数组的其实地址紧随结构体device之
* 后;这种声明方法可以巧妙的实现C语言里的数组扩展,比将reverse定义为指针,
* 再为指针分配空间的做法要简单一些,并且可以节省一个指针的存储空间
*/

};


int main()
{
    struct device * p_dev =
        (struct device *) malloc (sizeof(struct device) + sizeof(int)*25);
    
//sizeof(int)*25是数组reserve的具体空间(25个元素)

    p_dev->reserve[0] = 100;
    p_dev->reserve[24] = 0;

    printf("p_dev->reserve[0] = %d\n", p_dev->reserve[0]);
    printf("p_dev->reserve[24] = %d\n", p_dev->reserve[24]);
    printf("sizeof(struct device) = %d\n",sizeof(struct device));

    
//将结构体device之后的第一个内容(int值,其实就是reserve[0]的值) 赋值给a


    int a = *(&p_dev->count + 1);
    printf("a = %d\n", a);
    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-------->|

阅读(1129) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~