Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Returning 2D Arrays from a function
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
a22asin




PostPosted: 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;
        }
}


Sponsor
Sponsor
Sponsor
sponsor
Insectoid




PostPosted: 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.
a22asin




PostPosted: 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.
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: