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

C,数组大小必须是const表达式

发布时间:2020-12-16 09:58:05 所属栏目:百科 来源:网络整理
导读:参见英文答案 Declaring the array size with a non-constant variable????????????????????????????????????3个 我正在读Lappman的“C Primer”一书.在第113页它说 The number of elements in an array is part of the array’s type. As a result,the dime
参见英文答案 > Declaring the array size with a non-constant variable????????????????????????????????????3个
我正在读Lappman的“C Primer”一书.在第113页它说

The number of elements in an array is part of the array’s type. As a result,the dimension must
be known at compile time,which means that the dimension must be a constant
expression.

此外,它说我们不能做这样的事情

unsigned cnt  = 43; //not an const expression
string bad[cnt]; // error

但事实并非如此,我编译它没有任何问题,我甚至可以做到这样的事情

int i;
cin >> i;
get_size(i);

void get_size(int size) {
  int arr[size];
  cout << sizeof (arr);
}

它运行良好,为什么每本书都说在编译时必须知道数组大小?或者它必须是const表达式?

解决方法

因为那些书正在教你C.

确实,在C中.

您使用的是GCC提供的非标准扩展,称为可变长度数组.

如果打开所有编译器警告(应始终执行此操作),则会在构建期间通知您.

(编辑:李大同)

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

    推荐文章
      热点阅读