Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ error: invalid types 'int[int]' for array subscript

Tags:

c++

Trying to learn C++ and working through a simple exercise on arrays.

Basically, I've created a multidimensional array and I want to create a function that prints out the values.

The commented for-loop within Main() works fine, but when I try to turn that for-loop into a function, it doesn't work and for the life of me, I cannot see why.

#include <iostream>
using namespace std;


void printArray(int theArray[], int numberOfRows, int numberOfColumns);

int main()
{

    int sally[2][3] = {{2,3,4},{8,9,10}};

    printArray(sally,2,3);

//    for(int rows = 0; rows < 2; rows++){
//        for(int columns = 0; columns < 3; columns++){
//            cout << sally[rows][columns] << " ";
//        }
//        cout << endl;
//    }

}

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][y] << " ";
        }
        cout << endl;
    }
}
like image 825
Rick Avatar asked May 29 '11 01:05

Rick


2 Answers

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

like image 98
Ben Voigt Avatar answered Oct 21 '22 03:10

Ben Voigt


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);
like image 2
Frédéric Hamidi Avatar answered Oct 21 '22 03:10

Frédéric Hamidi