8 20 C:\Users\86198\Desktop\未命名1.cpp [Error] array bound is not an integer constant before ']' token
时间: 2023-12-12 11:54:26 浏览: 27
这个错误通常是由于数组的大小没有使用常量表达式来定义引起的。C++数组的大小必须是一个常量表达式,也就是在编译时就能确定大小的表达式。例如,以下代码会产生相同的错误:
```c++
int n;
cin >> n;
int arr[n]; // 错误,n 不是常量表达式
```
正确的定义方式是使用常量表达式或者使用动态内存分配:
```c++
const int N = 10; // 常量表达式
int arr[N];
int n;
cin >> n;
int* arr = new int[n]; // 动态内存分配
```
需要注意的是,使用动态内存分配后,需要手动释放内存:
```c++
delete[] arr;
```
相关问题
如何解决使用了const int但仍出现error: array bound is not an integer constant before ‘]’ token这种错误的情况
这种错误通常是因为使用了非常量表达式来定义数组的大小。如果你使用了const int,但仍然出现了这个错误,可以尝试以下两种解决方法:
1. 使用宏定义或枚举类型来定义数组大小,这些都是编译时常量,可以避免这个错误。
2. 如果你使用了c++11或更高版本,可以使用constexpr关键字定义常量表达式来替代const int,这样也可以避免这个错误。
例如,你可以这样定义一个数组大小:
```c++
#define ARRAY_SIZE 10
int myArray[ARRAY_SIZE];
```
或者:
```c++
enum { ARRAY_SIZE = 10 };
int myArray[ARRAY_SIZE];
```
或者:
```c++
constexpr int ARRAY_SIZE = 10;
int myArray[ARRAY_SIZE];
```
这样就可以避免出现“array bound is not an integer constant”的错误了。
[error] array bound is not an integer constant before ']' token
这个错误提示是因为在定义数组时,数组的大小不是一个整数常量。数组的大小必须是一个整数常量,不能是变量或表达式。
例如,下面的代码会出现这个错误:
int n = 10;
int arr[n]; // 错误:数组大小不是整数常量
正确的做法是将数组大小改为一个整数常量,例如:
#define N 10
int arr[N]; // 正确:数组大小是整数常量
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)