C:进行动态调整结构风格推荐 [英] C: Recommended style for dynamically sized structs

查看:111
本文介绍了C:进行动态调整结构风格推荐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过它的长度应是动态的Internet上传输的数据包。

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

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

的问题是,零长度数组不是符合ISO标准。

The problem is that zero-length arrays are not ISO-compliant.

我应该使用字符文件名[1]; 呢?但随后的sizeof(结构数据包)将不再返回正确的值。

Should I use char filename[1]; instead? But then sizeof(struct packet) will not return the correct value anymore.

推荐答案

经典问题。你可以简单地处理它(请注意,sizeof的(富)可能由多个熄灭如果编译器轮的结构尺寸起来,这是(我相信)允许的),或者你可以做这样的事情:

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];
};

这是烦人(你必须使用h.id等),但它的作品。通常我只是处理它是一个,但上面可能会稍微更便携。

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.

这篇关于C:进行动态调整结构风格推荐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆