Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1446506
  • 博文数量: 254
  • 博客积分: 8696
  • 博客等级: 中将
  • 技术积分: 2961
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-03 16:46
文章分类

全部博文(254)

文章存档

2015年(4)

2014年(18)

2013年(16)

2012年(8)

2011年(25)

2010年(2)

2009年(74)

2008年(107)

分类: C/C++

2008-04-26 16:34:49

 
总结:
struct dirent{
.......
.......
char a[1];}
在这里char a[1];长度为1,一般认为作为字符数组只能存放'/0',但在这里a[1]声明是
放在结构体的最后,属于变长数据结构的使用,能够方便访问结构体后面的地址,如:
[Copy to clipboard] [ - ]CODE: 

struct dirent
{
   int len;
   char a[0];
};
struct dirent *fun(char *str, int len)
{
   struct dirent* n = (struct dirent*)malloc(len +1 + sizeof(struct dirent));
   if (!n)
      return NULL;
   n->len = len;
   memcpy(n->a, str, len);
   return n;
}

在使用malloc时扩展size,它正好在struct的尾端(char a[0]或char a[1]必须作为结构体最后成员),
在内存中,扩展的地址跟最后一个成员char p[0]相邻,也就是说通过p也可以实现访问,
用char p[0]比char *p的好处是:
(1) 前者malloc之后不需要给p赋值,因为前者是array.
(2) 前者实现了一个动态数组的功能,如果不需要,他根本就可以不占用任何内存,而后者会占用4个字节.
阅读(1406) | 评论(0) | 转发(0) |
0

上一篇:struct dirent成员

下一篇:rewinddir函数

给主人留下些什么吧!~~