@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的地址是緊隨結構體之后的。
【來源】