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

Here’s a variation that avoids the complicated array reference syntax: http://ideone.com/GVkxk

If the size is dynamic, you can’t 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

Leave a Comment