Skip to main content
gamedev.net
🔒 Locked

2d arrays

Started by wingman20 3 replies 550+ views
Original Post
wingman20
wingman20
is there a way to crete dynamic 2d arrays, like you can create dynamic 1d arryas (char*, int*, etc)? specificly 2d arrays of LPDIRECT3DTEXTURE8 and D3DMATERIAL8. thanks
Null and Void
Null and Void
In many cases it is better to simply create a 1D array of size width*height than to create a 2D array. But, if you''re sure you need to create a 2D array, just create a 1D array of pointers to pointers, then use a for loop to assign more memory to each pointer in that array.

"Finger to spiritual emptiness underlying everything." -- How a C manual referred to a "pointer to void." --Things People Said
Resist Windows XP''s Invasive Production Activation Technology!
http://druidgames.cjb.net/
IOFILE
IOFILE
Yes, there are two ways I know.

As stated by Null and Void, you could simply have an array of pointers and allocate each of them to be an array of structure types.

int **Array2d;
int X = 3, Y = 7;

Array2d = new int*[X];
for (int loop = 0; loop < X; loop++)
Array2d[loop] = new int[Y];
for (int lY = 0; lY < Y; lY++)
{
for (int lX = 0; lX < X; lX++)
{
Array2d[lX][lY] = lX+lY;
cout << Array2d[lX][lY] << " ";
}
cout << endl;
}

Or just have one big array (which is easier to both reference and manage, and a bit quicker computationally, but not much)

int *Array2d;
int X = 3, Y = 7;

Array2d = new int[X*Y];
for (int lY = 0; lY < Y; lY++)
{
for (int lX = 0; lX < X; lX++)
{
Array2d[lX*lY] = lX+lY;
cout << Array2d[lX*lY] << " ";
}
cout << endl;
}

both methods will get you this output!

0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8

Hope I helped
IOFILE
IOFILE
IOFILE
Yes, there are two ways I know.

As stated by Null and Void, you could simply have an array of pointers and allocate each of them to be an array of structure types.

int **Array2d;
int X = 3, Y = 7;

Array2d = new int*[X];
for (int loop = 0; loop < X; loop++)
Array2d[loop] = new int[Y];
for (int lY = 0; lY < Y; lY++)
{
for (int lX = 0; lX < X; lX++)
{
Array2d[lX][lY] = lX+lY;
cout << Array2d[lX][lY] << " ";
}
cout << endl;
}

Or just have one big array (which is easier to both reference and manage, and a bit quicker computationally, but not much)

int *Array2d;
int X = 3, Y = 7;

Array2d = new int[X*Y];
for (int lY = 0; lY < Y; lY++)
{
for (int lX = 0; lX < X; lX++)
{
Array2d[lX*lY] = lX+lY;
cout << Array2d[lX*lY] << " ";
}
cout << endl;
}

both methods will get you this output!

0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8

Hope I helped
IOFILE
IOFILE
IOFILE
Damn, I clicked the reply button twice. Sorry
IOFILE

Topic Locked

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

Sign in to reply to this topic.