C: Recommended style for dynamically sized structs

后端 未结 4 1756
轻奢々
轻奢々 2020-12-31 14:41

I need to transfer packets through the internet whose length should be dynamic.

struct packet
{
  int id;
  int filename_len;
  char filename[];
};
         


        
4条回答
  •  鱼传尺愫
    2020-12-31 15:20

    I suggest to use char filename[1] and include a terminating 0-byte. This way, you can malloc() the correct structure size and avoid one-off errors like this:

    ptr = malloc(sizeof(struct packet)+filename_len);
    strncpy(&ptr->filename, filename, filename_len);
    

    But the receiver must to know that it needs to read filename_len+1 bytes.

提交回复
热议问题