在读程序中经常会看到这样的定义char data[0],这是一个什么样的用法,有什么好处,在哪些地方用到?
本文的主要目的就是阐明这个定义的作用,以及适用范围,这需要对指针的概念和操作系统的内存模型有一个情形的认识。
首先看一段程序:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct _Info
{
int i;
char data[0];
}Info;
int main(int argc, char* argv[])
{
printf("%d/n",sizeof(Info));
return 0;
}
程序的执行结果是:4。整数i就占了4个字节,这表明data没有占用空间。data是一个数组名;该数组没有元素;该数组的真实地址紧随结构体Info之后;这种声明方法可以巧妙的实现C语言里的数组扩展。
记住上面的结构体不同于:
typedef struct _Info
{
int i;
char* data;
}Info;
这个结构体占用8个字节的空间,因为指针类型要占用4个字节的空间。
再看一个例子:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct _Info
{
int i;
char data[0];
}Info;
int main(int argc, char* argv[])
{
char buf[10] = "123456789";
void* p = NULL;
printf("%d/n",sizeof(Info));
Info* info = (Info*)malloc(sizeof(Info) + 10);
p = (void*)info->data;
printf("addr of info is %p. addr of data is %p ./n", info, p);
strcpy((char*)p, buf);
printf("%s/n", (char*)p);
return 0;
}
程序的执行结果见下图:
可知,data的地址是紧随结构体之后的。