加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C89中的数组声明中使用sizeof()

发布时间:2020-12-16 06:03:11 所属栏目:百科 来源:网络整理
导读:我的印象是C89中不可能有变量大小的数组声明.但是,当使用clang -ansi编译时,我可以运行以下代码: double array[] = { 0.0,1.0,2.0,3.0,4.0 };double other_array[sizeof(array)] = { 0.0 }; 这里发生了什么?这不是一个可变大小的数组声明吗? 解决方法 那
我的印象是C89中不可能有变量大小的数组声明.但是,当使用clang -ansi编译时,我可以运行以下代码:
double array[] = { 0.0,1.0,2.0,3.0,4.0 };
double other_array[sizeof(array)] = { 0.0 };

这里发生了什么?这不是一个可变大小的数组声明吗?

解决方法

那是因为sizeof运算符的结果是常量表达式,所以它不符合VLA的条件,就像下面的声明一样:
int other_array[5];

也不能是可变长度数组.来自C11(N1570)§6.6/ p6常数表达(强调我的未来):

An integer constant expression117) shall have integer type and shall
only have operands that are integer constants,enumeration constants,
character constants,sizeof expressions whose results are integer
constants
,_Alignof expressions,and floating constants that are the
immediate operands of casts.

为了完整起见,运算符的大小并不总是导致恒定表达式,尽管这仅影响C89后的标准(在C11的VLA中是可选的).参考§6.5.3.4/ p2 sizeof和_Alignof运算符:

If the type of the operand is a variable length array type,the
operand is evaluated; otherwise,the operand is not evaluated and the
result is an integer constant.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读