C ++数组-表达式必须具有常量值 [英] c++ array - expression must have a constant value

查看:232
本文介绍了C ++数组-表达式必须具有常量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从声明的变量创建数组时出现错误.

I get an error when I try to create an array from the variables I declared.

int row = 8;
int col= 8;
int [row][col];

为什么会出现此错误:

表达式必须具有恒定值.

expression must have a constant value.

推荐答案

创建这样的数组时,其大小必须恒定.如果要使用动态大小的数组,则需要在堆上为其分配内存,完成后还需要使用delete释放它:

When creating an array like that, its size must be constant. If you want a dynamically sized array, you need to allocate memory for it on the heap and you'll also need to free it with delete when you're done:

//allocate the array
int** arr = new int*[row];
for(int i = 0; i < row; i++)
    arr[i] = new int[col];

// use the array

//deallocate the array
for(int i = 0; i < row; i++)
    delete[] arr[i];
delete[] arr;

如果要固定大小,则必须将它们声明为const:

If you want a fixed size, then they must be declared const:

const int row = 8;
const int col = 8;
int arr[row][col];

也是

int [row][col];

甚至都没有提供变量名.

doesn't even provide a variable name.

这篇关于C ++数组-表达式必须具有常量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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