c++ error: invalid types int[int] for array subscript
c++ error: invalid types int[int] for array subscript
C++ inherits its syntax from C, and tries hard to maintain backward compatibility where the syntax matches. So passing arrays works just like C: the length information is lost.
However, C++ does provide a way to automatically pass the length information, using a reference (no backward compatibility concerns, C has no references):
template<int numberOfRows, int numberOfColumns>
void printArray(int (&theArray)[numberOfRows][numberOfColumns])
{
for(int x = 0; x < numberOfRows; x++){
for(int y = 0; y < numberOfColumns; y++){
cout << theArray[x][y] << ;
}
cout << endl;
}
}
Demonstration: http://ideone.com/MrYKz
Heres a variation that avoids the complicated array reference syntax: http://ideone.com/GVkxk
If the size is dynamic, you cant use either template version. You just need to know that C and C++ store array content in row-major order.
Code which works with variable size: http://ideone.com/kjHiR
Since theArray
is multidimensional, you should specify the bounds of all its dimensions in the function prototype (except the first one):
void printArray(int theArray[][3], int numberOfRows, int numberOfColumns);
c++ error: invalid types int[int] for array subscript
Im aware of the date of this post, but just for completeness and perhaps for future reference, the following is another solution. Although C++ offers many standard-library facilities (see std::vector
or std::array
) that makes programmer life easier in cases like this compared to the built-in array intrinsic low-level concepts, if you need anyway to call your printArray
like so:
printArray(sally, 2, 3);
you may redefine the function this way:
void printArray(int* theArray, int numberOfRows, int numberOfColumns){
for(int x = 0; x < numberOfRows; x++){
for(int y = 0; y < numberOfColumns; y++){
cout << theArray[x * numberOfColumns + y] << ;
}
cout << endl;
}
}
In particular, note the first argument and the subscript operation:
- the function takes a pointer, so you pass the name of the multidimensional array which also is the address to its first element.
- within the subscript operation (
theArray[x * numberOfColumns + y]
) we access the sequential element thinking about the multidimensional array as an unique row array.
Related posts on array subscript :
- TypeError: function object is not subscriptable – Python
- Error: int object is not subscriptable – Python
- bash – How to find the length of an array in shell?
- loops – VBScript create a multi-dimensional array and add to it?
- Dynamic vs static array in c
- Passing Arrays to Function in C++
- arrays – type any? has no subscript members
- C – error: subscripted value is neither array nor pointer