Advertisement

dynamic allocating of multi dimensional arrays

Started by March 13, 2003 04:57 AM
3 comments, last by knownonlyash 21 years, 8 months ago
hi is it possible to allocate a 2x2 array by using new? when i try it says its not a constant expression. i''m trying this because i want to create a terrain from an unknown sized bitmap. thanx h
yes it is possible. you do it like this:


  	int height = 10;	int width = 20;	int** array = new int*[width];	for ( int i = 0; i < width; i++ )		array[i] = new int[height];  

now you can access it as array[x][y]
and to delete the array when it''s no longer needed:

  		for ( int j = 0; j < width; j++ )		delete [] array[j];	delete [] array;  


My Homepage
Advertisement
sweet. i''ll give it a try. thanx
I''d probably use std::vector instead.

Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions
[sarcasm]
Thank you for sharing thatsiaspete, we really wanted to know what you'd use... no, really .
[/sarcasm]

Anywho, yes, std vectors can be useful, but sometimes it's more important to understand how things work, not just that... hey I can use this, then you get a job, and you've got a C compiler that has no std vector, and you have no clue how to implement something yourself.

knownonlyash: You could simply use a 1 dimensional array just as easily you know.

unsigned char *Buffer = new[bmpWidth*bmpHeight*bmpByteDepth];
Then to access any x,y location, you can use this (assuming 8bits/1byte because you said a terrain from the bitamp):
#define GetPixel(x,y) (Buffer[y*bmpWidth+x])


Then you can call GetPixel(x,y) and it will return the correct index, instead of dealing with a 2 dimensional array (it really isn't a 2 dimensional array, it's actually an array of pointers). The only time I ever found myself using a dynamic 2-dimensional array was back in the day (borland turbo c/c++ for dos) when the maximum single array size was 65535, so I had to use this idea to have arrays larger than this . In the days of 32-bit compilers, this isn't a problem anymore, so simply using a 1d array is much more efficient.

--- Edit ---
My sarcasm tags didn't show.

[edited by - Ready4Dis on March 13, 2003 8:45:21 AM]

This topic is closed to new replies.

Advertisement