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

查看:38
本文介绍了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];

为什么我会收到此错误:

Why do I get this error:

表达式必须有一个常量值.

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];

甚至不提供变量名.

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

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