Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4842500
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: LINUX

2009-02-06 14:03:16

可以使用info gcc "c ext" zero指令查看

5.11 Arrays of Length Zero
==========================

Zero-length arrays are allowed in GNU C. They are very useful as the
last element of a structure which is really a header for a
variable-length object:

     struct line {
       int length;
       char contents[0];
     };

     struct line *thisline = (struct line *)
       malloc (sizeof (struct line) + this_length);
     thisline->length = this_length;

 In ISO C90, you would have to give `contents' a length of 1, which
means either you waste space or complicate the argument to `malloc'
.



#include <stdlib.h>
#include <stdio.h>
struct device{
    int count;
    int reserve[0]; //reserve是一个数组名;该数组没有元素;该数组的其实地址紧随结构题device之后;这种声明方法可以巧妙的实现C语言里的数组扩展

};

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

    p_dev->reserve[0] = 10;
    p_dev->reserve[24] = 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);

    int a = *(&p_dev->count + 1);
    printf("a = %d\n", a);
}

[root@zj cstudy]# gcc -o array0 array0.c
[root@zj cstudy]# ./array0
p_dev->reserve[24] = 0
sizeof(struct device) = 4
a = 10

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