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

当在函数外部声明时,为什么数组大小参数不是变量?

发布时间:2020-12-16 07:23:57 所属栏目:百科 来源:网络整理
导读:参见英文答案 In C,why can’t a const variable be used as an array size initializer? ????????????????????????????????????3个 为什么在C99中将变量作为大小参数声明在函数外部是不可能的? 例如,请考虑此代码段. 它会导致错误:在文件范围编译错误时可
参见英文答案 > In C,why can’t a const variable be used as an array size initializer? ????????????????????????????????????3个
为什么在C99中将变量作为大小参数声明在函数外部是不可能的?

例如,请考虑此代码段.
它会导致错误:在文件范围编译错误时可变地修改’矩阵’.

static int const height = 5;
static int const width = 5;
static int const matrix[height][width] = { ... };

int main(void){ ... }

我知道c中的const并不意味着不变.这意味着“只读”,但我没有正确理解它有什么影响.
那么为什么数组不能从只读内存中获取它们的大小呢?

我知道这个问题可以用#definesenum解决,所以我更感兴趣的是解释为什么会这样.

解决方法

C99 6.7.5.2/2数组声明符:

Only ordinary identifiers (as defined in 6.2.3) with both block scope or function prototype scope and no linkage shall have a variably modified type. If an identifier is declared to be an object with static storage duration,it shall not have a variable length array type.

(编辑:李大同)

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

    推荐文章
      热点阅读