开发者

Meaning of char arr[0] [duplicate]

开发者 https://www.devze.com 2023-01-14 18:17 出处:网络
This question already has answers here: 开发者_JAVA技巧 Closed 12 years ago. Possible Duplicate: Array of zero length
This question already has answers here: 开发者_JAVA技巧 Closed 12 years ago.

Possible Duplicate:

Array of zero length

I have seen such type of code :-

#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;

}

I was wondering the meaning of arr[0]. I mean in what scenarios do we need to use arr[0]. What purpose does it serve?


In C, the members of a struct are always allocated in the order they appear. So, my_pkt->data is a pointer "one past the end" of a pkt object. If initialized with

my_pkt = malloc( sizeof( struct pkt ) + 50 );

then my_pkt->data points to the beginning of a 50-byte general-purpose buffer.

Only the final member of a struct is allowed to be defined this way.

To be more compliant with C99, omit the 0 and write char data[];.


It's a flexible array member, that can be used, when you need a structure of varying size. It simplifies the allocation of the extra size, just see the link.


This is what the GCC Manual has to say about zero length arrays


This is a zero byte array. Used to append data of arbitrary size at runtime. Very useful in sending data over a socket.

You should refer this for more details- http://bytes.com/topic/c/answers/547407-char-data-0-a


char arr[0] is a same as char *. And the reason you are getting segmentation fault is,because when you do calloc in following line of code

p_t *p = (p_t *)calloc(1, sizeof(p_t));

it actually initialize every memory with zero.So when you passed a null pointer,it caused segmentation fault because of null pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消