无法创建具有恒定大小的数组(“预期的常量表达式") [英] Can't create array with constant size ("expected constant expression”)

查看:31
本文介绍了无法创建具有恒定大小的数组(“预期的常量表达式")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与 Windows 10 上的 Visual Studio(社区 2015)中的 C 相关.

This question pertains to C in Visual Studio (Community 2015) on Windows 10.

我似乎无法创建具有常量大小的数组 - 下面的代码会导致预期的常量表达式"错误,从而阻止构建.这是一个 wchar_t 数组,大小为 size_t,但我看到 char & 的行为相同.其他数组类型int 常量.

I can't seem to create an array with a const size - the below code causes an "expected constant expression" error that prevents build. It's a wchar_t array here with a size_t size, but I see the same behavior for char & other array types & int constants.

我知道需要在编译时知道数组的大小,但这里肯定就是这种情况.什么给?

I know the size of arrays needs to be known at compile time, but surely that's the case here. What gives?

#include <stdio.h>

void main()
{
    size_t const newsize = 100;

    wchar_t fileData[newsize];
}

推荐答案

我知道需要在编译时知道数组的大小,但这里肯定就是这种情况.

I know the size of arrays needs to be known at compile time, but surely that's the case here.

事实并非如此.在 C 中,const 限定不会产生常量表达式".所以 newsize 不是 常量表达式(与 C++ 不同).

That's actually not the case. In C, const qualifying doesn't result in a "constant expression". So newsize isn't a constant expression (unlike C++).

您的代码在 C99 和 C11 中有效,如果可变长度数组(VLA) 由您的实现支持(VLA 在 C11 中是可选的).但是,Visual Studio 似乎不支持 VLA,并期望像 C89 中那样对数组大小使用常量表达式".

Your code is valid in C99 and in C11, if variable length array (VLA) is supported by your implementation (VLAs are optional in C11). However, it seems Visual studio doesn't seem to support VLAs and expects a "constant expression" for array size as in C89.

所以你可能不得不使用动态内存分配(malloc &朋友),或者简单地指定100作为大小,或者使用宏来定义大小等等.

So you may have to use dynamic memory allocation (malloc & friends), or simply specify the 100 as size, or use a macro for defining size and so on.

这篇关于无法创建具有恒定大小的数组(“预期的常量表达式")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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