C Struct Hack

It's not clear if it's legal or portable, but it is rather popular.

#include <stdlib.h>
#include <string.h>

struct line {
  int length;
  char contents[]; // Flexible array member
};

int main()
{
  int this_length = 20;
  struct line* this_line
    = (struct line*) malloc(sizeof(struct line) + sizeof(char) * this_length);
  this_line->length = this_length;
  strcpy(this_line->contents, "Hello world!");
  free(this_line);

  return 0;
}

GNU C要求extra data位于non-empty top-level object的末尾。

参考文章:

http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

http://c-faq.com/struct/structhack.html

原文地址:https://www.cnblogs.com/chenkkkabc/p/3182019.html