Pointers to Multidimensional Arrays

Started by
2 comments, last by ctt 20 years ago
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.
Advertisement
Few ways to do it.

//by referencevoid fun(int (&p)[50][50]){}//by valuevoid fun(int p[50][50]){}//by value againvoid fun(int p[][50]){}//by pointervoid 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]
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 pointersgameboard **ppboard;for(int i=0;i<50;i++)  // for each pointer    board = new gameboard [50];  // create an array of 50 gameboards<br> </pre> <br><br>Now you can assign ppboard to board, and pass it around, etc. Just be sure to delete your mem as follows:<br><br><pre><br>for(int i=0;i<50;i++)<br>    delete [] board;<br>  </pre>   <br>  <br>   <br><br><SPAN CLASS=editedby>[edited by - BriTeg on April 5, 2004 11:03:51 AM]</SPAN>
Brianmiserere nostri Domine miserere nostri
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.

This topic is closed to new replies.

Advertisement