C: Recommended style for dynamically sized structs

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

    I think you should look at some existing examples of dynamically sized structures for guidance here. The best example I know of are the TOKEN APIs in Win32. They use the macro ANYSIZE_ARRAY which just resolves down to 1. Raymond Chen did an extensive blog article detailing exactly why they are done this way

    • https://devblogs.microsoft.com/oldnewthing/20040826-00/?p=38043

    As for operations such as sizeof failing. This will fail no matter what solution you choose for a dynamically sized struct. sizeof is a compile time operation and you will be re-sizing the structure at runtime. It simply cannot work.

提交回复
热议问题