C: Recommended style for dynamically sized structs

后端 未结 4 1767
轻奢々
轻奢々 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:10

    Classic issue. You can simply deal with it (and note that sizeof(foo) may be off by more than one if the compiler rounds the structure size up, which is (I believe) allowed), or you can do something like this:

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

    This is annoying (you have to use h.id, etc), but it works. Usually I just deal with it being one, but the above might be marginally more portable.

提交回复
热议问题