One way that I figured out, was to allocate a single
dimensional array and then use it as a two dimensional
array like .....
int row ; // no of rows
int col ; // no of columns
int *ptr ;
ptr = new int [row * col];
But this has two problems....
1. It requires access computations
2. For multidimensional arrays it would become really
cumbersome
Can I do it in any other way...?
Thanks ...
win
* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!
Here is one simple way --
const char sx = 20;
const char sy = 30;
const char sz = 40;
int (*array)[sy][sz] = new int[sz][sy][sz];
-- and, later, required:
delete [] array;
--
Paul Lutus
www.arachnoid.com
win <h_s_sN...@vsnl.com.invalid> wrote in message
news:22e9217f...@usw-ex0102-014.remarq.com...
I am sorry, but i am a newbie and still a bit weak at pointers,
so could u please explain your code a bit in detail.......
i would be really greatful...
> I have a slight problem with dynamic memory allocation,
> I can't seem to figure out how I can allocate a two or
> three dimensional array .
[ snip ]
http://www.cerfnet.com/~mpcline/On-Line-C++-FAQs/freestore-mgmt.html#[16.15]
--
Cheers, // The alt.comp.lang.learn.c-c++ FAQ:
Rich. // http://www.raos.demon.co.uk/acllc-c++/faq.html
>The size of the array is known only when the user is prompted
>for the size.
>
>I am sorry, but i am a newbie and still a bit weak at pointers,
>so could u please explain your code a bit in detail.......
If you don't know anything about the array then you're (usually) into
an array of pointers. A pointer can be treated as though it were the
address of element zero of an array. (ie *p = p[0]). A single
dimensional array is easy enough...
int a[10]; //"*a = -1" is same as "a[0] = -1"
//"*(a + 1) = -2" same as "a[1] = -2"
That is, "a[x] = *((a) + (x))".
A two dimensional array is therefore "lots of one dimensional arrays",
or in other words, an array of (one dimensional) arrays. So, "a[][] =
**a"...
int
main()
{const int NX =3,
NY =2;
int ** a; //a[][]
//array of pointers
a = new int* [NY];
//for each pointer element
for (int y = 0; y < NY; y++)
//declare an array (remember a[] = *a)
a[y] = new int[NX]
;
//stuff some values in...
for (int y = 0; y < NY; y++)
for (int x = 0; x < NX; x++)
a[y][x] = y * 10 + x
;
//print them out...
for (int y = 0; y < NY; y++)
for (int x = 0; x < NX; x++)
cout << "a[" << y << "][" << x << "]=" << a[y][x] << endl
;
//trash the "2d array's" 1d arrays...
for (int y = 0; y < NX; y++)
//by doing each 1d array
delete [] a[y]
;
//and finally the array of pointers "new int*[NY]" can go...
delete [] a;
return 0;
}
Finally, note that there are much more advanced tools available in
C++. The STL containers are well worth a look - <vector>, <list> etc.