Archived

This topic is now archived and is closed to further replies.

Pointers to Multidimensional Arrays

This topic is 4998 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m having trouble assigning a pointer to a multidimensional array: gameboard board[50][50]; gameboard **pboard; basically I want to assign my pointer (pboard) to (board) so I can pass it into my function: Initboard(gameboard **ptogameboard); Thanks.

Share this post


Link to post
Share on other sites
Few ways to do it.


//by reference

void fun(int (&p)[50][50])
{}

//by value

void fun(int p[50][50])
{}

//by value again

void fun(int p[][50])
{}

//by pointer

void funbypointer(int (*p)[50][50])
{}

int p[50][50];
fun(p);
funbypointer(&p);


Hope that helps


[edited by - Jingo on April 5, 2004 10:45:13 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by ctt
I'm having trouble assigning a pointer to a multidimensional array:

gameboard board[50][50];
gameboard **pboard;

basically I want to assign my pointer (pboard) to (board) so I can pass it into my function:

Initboard(gameboard **ptogameboard);



First, your first declaration seems odd to me. Are you sure you want a 50x50 array of gameboards? That's 2,500 gameboards. Shouldn't you have a single gameboard, made of 50x50 pieces (squares, whatever).

Anyway, assuming I'm just unclear about that, think about what each variable is: board is a pointer to a 50x50 array, pboard is a pointer to a pointer (and thus should be called ppboard, or something). There are probably lots of ways to do what you want, but I would rewrite it like this:


gameboard *board[50]; // board is an array of 50 pointers
gameboard **ppboard;

for(int i=0;i<50;i++) // for each pointer
board[ i ] = new gameboard [50]; // create an array of 50 gameboards


Now you can assign ppboard to board, and pass it around, etc. Just be sure to delete your mem as follows:


for(int i=0;i<50;i++)
delete [] board[ i ];




[edited by - BriTeg on April 5, 2004 11:03:51 AM]

Share this post


Link to post
Share on other sites
yeah I realized I made a mistake in variable naming.. it really should be a 50x50 array of gameTILES. But, anyways, thanks for all the help and I think this did the trick:

gametile board[50][50];
gametile (*pboard)[50][50];

and my function as:

//by pointer
void funbypointer(gametile (*pboard)[50][50]){}

I don''t think that I needed that double pointer.

Share this post


Link to post
Share on other sites