搜索
bottom↓
回复: 4

sizeof 中的数组[]中为空,不计大小? Zero-length arrays

[复制链接]

出0入0汤圆

发表于 2014-5-21 11:46:32 | 显示全部楼层 |阅读模式
本帖最后由 peixiuhui 于 2014-5-21 17:38 编辑

1
  2
  3 #include <stdio.h>
  4
  5 struct gpio_led_data {
  6     unsigned gpio;
  7     unsigned char new_level;
  8     unsigned char can_sleep;
  9     unsigned char active_low;
10     unsigned char blinking;
11 };
12
13 struct gpio_led_priv {
14     int num_leds;
15     struct gpio_led_data leds[];
16 };
17
18 int main(int argc, char *argv[])
19 {
20     printf("sizeof:=%d\n",sizeof(struct gpio_led_priv));
21 }

为什么 输出 sizeof:=4 ???


阿莫论坛20周年了!感谢大家的支持与爱护!!

一只鸟敢站在脆弱的枝条上歇脚,它依仗的不是枝条不会断,而是自己有翅膀,会飞。

出0入0汤圆

发表于 2014-5-21 12:01:02 | 显示全部楼层
你在提問前,有試過
  1. struct gpio_led_priv {
  2.     int num_leds;
  3.     struct gpio_led_data leds[1];
  4. };
复制代码

嗎?

出0入0汤圆

发表于 2014-5-21 12:13:19 | 显示全部楼层
本帖最后由 dr2001 于 2014-5-21 12:31 编辑

C99/N1256 6.7.2.1-16 flexible array member.

https://gcc.gnu.org/onlinedocs/g ... th.html#Zero-Length

所以,结果是对的。

这种声明直接用是方便的,能让代码更干净一些。
但这种结构体如果嵌套在别的结构体声明里,会因为不定长的成员导致无法决定其后边的成员的地址,有的编译器可能会报错。

出0入0汤圆

发表于 2014-5-21 12:27:20 | 显示全部楼层
学习了!!!!!

出0入0汤圆

 楼主| 发表于 2014-5-21 13:51:12 | 显示全部楼层
dr2001 发表于 2014-5-21 12:13
C99/N1256 6.7.2.1-16 flexible array member.

https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Zero-Lengt ...

谢 了。

Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object:

     struct line {
       int length;
       char contents[0];
     };
     
     struct line *thisline = (struct line *)
       malloc (sizeof (struct line) + this_length);
     thisline->length = this_length;

In ISO C90, you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.

In ISO C99, you would use a flexible array member, which is slightly different in syntax and semantics:

回帖提示: 反政府言论将被立即封锁ID 在按“提交”前,请自问一下:我这样表达会给举报吗,会给自己惹麻烦吗? 另外:尽量不要使用Mark、顶等没有意义的回复。不得大量使用大字体和彩色字。【本论坛不允许直接上传手机拍摄图片,浪费大家下载带宽和论坛服务器空间,请压缩后(图片小于1兆)才上传。压缩方法可以在微信里面发给自己(不要勾选“原图),然后下载,就能得到压缩后的图片】。另外,手机版只能上传图片,要上传附件需要切换到电脑版(不需要使用电脑,手机上切换到电脑版就行,页面底部)。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|Archiver|amobbs.com 阿莫电子技术论坛 ( 粤ICP备2022115958号, 版权所有:东莞阿莫电子贸易商行 创办于2004年 (公安交互式论坛备案:44190002001997 ) )

GMT+8, 2024-5-20 07:12

© Since 2004 www.amobbs.com, 原www.ourdev.cn, 原www.ouravr.com

快速回复 返回顶部 返回列表