Skip to main content
GameDev.net gamedev.net
🔒 Locked

c++ 2-dimensional array

Started by lakibuk Oct 18, 2000 at 4:22 PM 7 replies 700+ views
Original Post
lakibuk
lakibuk
how can i pass a pointer to a 2-dimensional array to a procedure ? kind of: pointer to int[50][50] pseudocode: drawArea(pointer to int[50][50]); //procedure-call void drawArea(pointer to int[50][50] ptr) { //procedure for x=0 to 50; for y=0 to 50: drawTile(*ptr[x][y]); }}
lakibuk
lakibuk
but i dont want to make a new array, i want to pass a pointer of an already exiting array, so that i can read the values of the array in the procedure.
MicahJon
MicahJon
lakibuk,

You might try using vectors instead:

    
typedef std::vector< std::vector< int > > Int2DArray;
Int2DArray My2DArray;
Function(Int2DArray& ArrayToPass);


Or create a struct whose only member is the 2D array, and pass the struct.

There are other methods by which to pass the 2D array directly, but they start to get ugly, and bug prone.

Micah
JonStelly
JonStelly


int Fill2DArray(int *pArray[], int nWidth, int nHeight)
{
for(int i=0; i < nWidth; i++){
for(int j=0; j < nHeight; j++){
pArray[j] = 1;
}
}
return 0;
}

int main(...)
{
int *pArray[10];

for(int i=0; i < 10; i++){
pArray[i] = new int[10];
for(int j=0; j < 10; j++){
pArray[i][j] = 0;
}
}

Fill2DArray(pArray, 10, 10);

for(i=0; i < 10; i++){
for(int j=0; j < 10; j++){
cout << _T("pArray[") << i << _T("][") << j << _T("] = ") << pArray[i][j] << endl;
}
}
}

spunge
spunge
If you only want to pass a pointer to a 2D-array you need to define your procedure like this:

void drawArea(int array[][50]) {
int x,y;
for (x=0; x < 50; x++)
for (y=0; y < 50; y++)
drawTile(array[x][y]);
}

Then you call it like this:

int myarray[50][50];
drawArea(myarray);

Note that this requires that you hardcode the number of columns in your array (unless you''re on a UNICOS/mk system, which I guess you aren''t). The number of rows can be anything. It may not be the best or most practical solution, but I think this is what you were asking about.
Neuro
Neuro
Or instead of hard coding the number inside of the function, you can also pass in two integers into the function along with the array which are the dimentions.

Just makes the function more dynamic, that would be the only change though.

-----------------------------------------------
All messages are of my own personal opinion and
not meant to offend. But if they do - tough :)

Neuro.
-----------------------------------------------All messages are of my own personal opinion and not meant to offend. But if they do - tough :)Neuro.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.