變長資料結構

來源:互聯網
上載者:User
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個位元組.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.