C++ 数组下标的无效类型“int[int]”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/363864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
invalid types 'int[int]' for array subscript
提问by user33061
This code throws up the compile error given in the title, can anyone tell me what to change?
这段代码抛出了标题中给出的编译错误,谁能告诉我要更改什么?
#include <iostream>
using namespace std;
int main(){
int myArray[10][10][10];
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++x){
for (int y = 0; y <= 9; ++y){
myArray[i][t][x][y] = i+t+x+y; //This will give each element a value
}
}
}
}
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++x){
for (int y = 0; y <= 9; ++y){
cout << myArray[i][t][x][y] << endl;
}
}
}
}
system("pause");
}
thanks in advance
提前致谢
回答by coppro
You are subscripting a three-dimensional array myArray[10][10][10]
four times myArray[i][t][x][y]
. You will probably need to add another dimension to your array. Also consider a container like Boost.MultiArray, though that's probably over your head at this point.
您正在myArray[10][10][10]
四次下标一个 3 维数组myArray[i][t][x][y]
。您可能需要向数组添加另一个维度。还可以考虑使用Boost.MultiArray 之类的容器,尽管此时您可能无法理解。
回答by jmucchiello
What to change? Aside from the 3 or 4 dimensional array problem, you should get rid of the magic numbers (10 and 9).
要改变什么?除了 3 维或 4 维数组问题之外,您应该摆脱幻数(10 和 9)。
const int DIM_SIZE = 10;
int myArray[DIM_SIZE][DIM_SIZE][DIM_SIZE];
for (int i = 0; i < DIM_SIZE; ++i){
for (int t = 0; t < DIM_SIZE; ++t){
for (int x = 0; x < DIM_SIZE; ++x){
回答by Cadoo
int myArray[10][10][10];
should be
应该
int myArray[10][10][10][10];
回答by DShook
You're trying to access a 3 dimensional array with 4 de-references
您正在尝试访问具有 4 个取消引用的 3 维数组
You only need 3 loops instead of 4, or int myArray[10][10][10][10];
你只需要 3 个循环而不是 4 个,或者 int myArray[10][10][10][10];
回答by ABHISHEK YADAV
I think that you had intialized a 3d array but you are trying to access an array with 4 dimension.
我认为您已经初始化了一个 3d 数组,但您正在尝试访问一个 4 维数组。
回答by Vishal Gupta
Just for completeness, this error can happen also in a different situation: when you declare an array in an outer scope, but declare another variable with the same name in an inner scope, shadowing the array. Then, when you try to index the array, you are actually accessing the variable in the inner scope, which might not even be an array, or it might be an array with fewer dimensions.
为了完整起见,此错误也可能发生在不同的情况下:当您在外部作用域中声明一个数组,但在内部作用域中声明另一个同名变量时,会遮蔽该数组。然后,当您尝试对数组进行索引时,您实际上是在访问内部作用域中的变量,该变量甚至可能不是数组,也可能是维数较少的数组。
Example:
例子:
int a[10]; // a global scope
void f(int a) // a declared in local scope, overshadows a in global scope
{
printf("%d", a[0]); // you trying to access the array a, but actually addressing local argument a
}