【转】char data[0]用法总结

@2019-07-31

1 struct MyData 
2 {
3     int nLen;
4     char data[0];
5 }; 

开始没有理解红色部分的内容,上网搜索下,发现用处很大,记录下来。

        
在结构中,data是一个数组名;但该数组没有元素;该数组的真实地址紧随结构体MyData之后,而这个地址就是结构体后面数据的地址(如果给这个结构体分配的内容大于这个结构体实际大小,后面多余的部分就是这个data的内容);这种声明方法可以巧妙的实现C语言里的数组扩展。


实际用时采取这样:
  struct MyData *p = (struct MyData *)malloc(sizeof(struct MyData )+strlen(str)),这样就可以通过p->data 来操作这个str。

示例:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 struct MyData 
 6 {
 7     int nLen;
 8     char data[0];
 9 };
10 
11 int main()
12 {
13     int nLen = 10;
14     char str[10] = "123456789";
15 
16     cout << "Size of MyData: " << sizeof(MyData) << endl;
17 
18     MyData *myData = (MyData*)malloc(sizeof(MyData) + 10);
19     memcpy(myData->data,  str, 10);
20 
21     cout << "myData's Data is: " << myData->data << endl;
22 
23     free(myData);
24 
25     return 0;
26 }

输出:

  Size of MyData: 4
  myData's Data is: 123456789        
由于数组没有元素,该数组在该结构体中分配占用空间,所以sizeof(struct Mydata) = 4。
malloc申请的是14个字节的连续空间,它返回一个指针指向这14个字节,强制转换成struct INFO的时候,前面4个字节被认为是Mydata结构,后面的部分拷贝了“123456789”的内容。

在读程序中经常会看到这样的定义char data[0],这是一个什么样的用法,有什么好处,在哪些地方用到?

本文的主要目的就是阐明这个定义的作用,以及适用范围,这需要对指针的概念和操作系统的内存模型有一个情形的认识。

首先看一段程序:

 1 #include <stdio.h>
 2 
 3 #include <string.h>
 4 
 5 #include <stdlib.h>
 6 
 7  
 8 
 9 typedef struct _Info
10 
11 {
12 
13     int i;
14 
15     char data[0];
16 
17 }Info;
18 
19  
20 
21 int main(int argc, char* argv[])
22 
23 {
24 
25     printf("%d/n",sizeof(Info));
26 
27     return 0;
28 
29 }

程序的执行结果是:4。

整数i就占了4个字节,这表明data没有占用空间。data是一个数组名;该数组没有元素;该数组的真实地址紧随结构体Info之后;这种声明方法可以巧妙的实现C语言里的数组扩展。

记住上面的结构体不同于:

1 typedef struct _Info
2 
3 {
4 
5     int i;
6 
7     char* data;
8 
9 }Info;

这个结构体占用8个字节的空间,因为指针类型要占用4个字节的空间。

再看一个例子:

 1 #include <stdio.h>
 2 
 3 #include <string.h>
 4 
 5 #include <stdlib.h>
 6 
 7 typedef struct _Info
 8 {
 9     int i;
10 
11     char data[0];
12 
13 }Info;
14 
15 
16 
17 int main(int argc, char* argv[])
18 {
19 
20     char buf[10] = "123456789";
21 
22     void* p = NULL;
23 
24 
25     printf("%d\n",sizeof(Info));
26 
27     Info* info = (Info*)malloc(sizeof(Info) + 10);
28 
29     p = (void*)info->data;
30 
31     printf("addr of info is %p. addr of data is %p ./n", info, p);
32 
33 
34     strcpy((char*)p, buf);
35 
36     printf("%s\n", (char*)p);
37 
38     return 0;
39 }

程序的执行结果:

  4
  addr of info is 0x188b020. addr of data is 0x188b024 .
  123456789

可知,data的地址是紧随结构体之后的。

来源

猜你喜欢

转载自www.cnblogs.com/skullboyer/p/11275070.html
今日推荐