Computer Science Canada

Returning 2D Arrays from a function

Author:  a22asin [ Tue Sep 30, 2014 11:56 am ]
Post subject:  Returning 2D Arrays from a function

Hi, im trying to pass a 2d array to a function, then have the function modify the 2d array and return it back to the main. But im having trouble doing so. i Tried calling by reference so that i dont need to return, but with no luck. This is what i got:

code:


       //main
        int cell[MAX_CELL][3]; // where [n][0] = state of cell, [n][1] = x cords and [n][3] = y cords

        cout << "How many occupied cells would you like to make: ";
        cin >> occupied;
        cout << "How many steps should be preformed: ";
        cin >> steps;

        createCell(cell, occupied);



void createCell(int &c[][3], int s){
        for (int i = 0; i >= s; i++){
                c[i][0] = 1;
                c[i][1] = rand%MAX_X;
                c[i][2] = rand%MAX_Y;
        }
}



Author:  Insectoid [ Tue Sep 30, 2014 1:17 pm ]
Post subject:  RE:Returning 2D Arrays from a function

Because an array is basically a pointer, it passes by reference automatically. What you have done here is pass a reference to that pointer instead of the pointer itself. Is like a pointer to a pointer. And since it's a 2d array, it's like a pointer to a pointer to a pointer!

Removing that ampersand should fix it, but if not, then using int **c as your first argument should work as well, though some people might not like that.

Author:  a22asin [ Tue Sep 30, 2014 1:40 pm ]
Post subject:  RE:Returning 2D Arrays from a function

ok, well i havent learned pointers yet so thats why im not sure how to use em.


: