char arr [0]的含义

Ash*_*ish 1 c

可能重复:
零长度的数组

我见过这种类型的代码: -

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

struct pkt {
  int pk_type;
  int tag;
  int magic_num;
  char data[0];  <-------- what does this mean ???
}__attribute__((packed));

typedef struct pkt p_t;
int main(void)
{
  p_t *p = (p_t *)calloc(1, sizeof(p_t));
  if(!p) {
    perror("p");
    return -1;
  }
  p->pk_type = 1;
  p->tag = 0xb00bbabe;
  p->magic_num = 0xcafebabe;
  strcpy("hello world", p->data); <-- Seg faults here !!!  

  return 0;

}
Run Code Online (Sandbox Code Playgroud)

我想知道arr [0]的含义.我的意思是在什么情况下我们需要使用arr [0].它有什么用途?

Pot*_*ter 7

在C中,a的成员struct总是按它们出现的顺序分配.所以,my_pkt->data是一个指针"一个接一个结束"的pkt对象.如果用.初始化

my_pkt = malloc( sizeof( struct pkt ) + 50 );
Run Code Online (Sandbox Code Playgroud)

然后my_pkt->data指向一个50字节的通用缓冲区的开头.

只允许以这种方式定义结构的最终成员.

为了更符合C99,省略0并写入char data[];.

  • 首先,零大小的数组声明在所有C语言版本中都是非法的.其次,`my_pkt-> data`实际上不是指针. (2认同)