以下结构:ios
struct MyData
{
int nLen;
char data[0];
};
在结构中,data是一个数组名;但该数组没有元素;该数组的真实地址紧随结构体MyData以后,而这个地址就是结构体后面数据的地址(若是给这个结构体分配的内容大于这个结构体实际大小,后面多余的部分就是这个data的内容);数组
这种声明方法能够巧妙的实现C语言里的数组扩展。spa
实际用时采起这样:操作系统
struct MyData *p = (struct MyData *)malloc(sizeof(struct MyData )+strlen(str)).net
这样就能够经过p->data 来操做这个str。指针
示例:blog
#include <iostream>内存
using namespace std;get
struct MyData
{
int nLen;
char data[0];
};stringint main()
{
int nLen = 10;
char str[10] = "123456789";cout << "Size of MyData: " << sizeof(MyData) << endl;
MyData *myData = (MyData*)malloc(sizeof(MyData) + 10);
memcpy(myData->data, str, 10);cout << "myData's Data is: " << myData->data << endl;
free(myData);
return 0;
}
输出:
Size of MyData: 4
myData's Data is: 123456789
因为数组没有元素,该数组在该结构体中分配占用空间,因此sizeof(struct Mydata) = 4。
malloc申请的是14个字节的连续空间,它返回一个指针指向这14个字节,强制转换成struct INFO的时候,前面4个字节被认为是Mydata结构,后面的部分拷贝了“123456789”的内容。
在读程序中常常会看到这样的定义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个字节的空间。
提问:能不能这样用Info a??? 若是以定义变量的形式定义Info a。会不会遇到a.data这个地址被占用,而后再用致使不可预想的问题???????