Click to See Complete Forum and Search --> : 2d character array dynamic allocation
benny
May 27th, 1999, 12:23 PM
I want to allocate a two dimensional character array dynamically. I tried with various methods and failed.
buffer[max][30];
max is a variable so I want to allocate dynamically. Is anyone there to help. Thanks in advance.
Joel.
You should be able to do:
char** ppBuffer = new char*[nWidth];
for( int c = 0; c < nWidth; c++ )
{
ppBuffer[ c ] = new char[ nHeight ];
}
//do stuff...
delete [ ] [ ] ppBuffer;
benny
May 27th, 1999, 10:59 PM
Thanks I got it. But a sball correction in delete.
char** ppBuffer = new char*[nWidth];
for( int c = 0; c < nWidth; c++ )
{
ppBuffer[ c ] = new char[ nHeight ];
}
//do stuff...
for( int c = 0; c < nWidth; c++ )
{
delete [] ppBuffer[ c ];
}
delete [ ] ppBuffer;
This is working Fine.
Joel.
Jan-Klaas
May 28th, 1999, 02:21 AM
Hi Joel,
the solution with everything allocated dynamically is necessary only if you don't know the length of the strings from which you want to build an array at compilation time. However, since in your example you know the second dimension (30), you can allocate memory for your array this way:
typedef char MyStringType[30];
void main()
{
MyStringType* pArray;
int max = 10;
pArray = new MyStringType[max];
// Do something;
delete[] pArray;
}
This is faster, easier and doesn't fragment your memory so much.
Greetings
Jan-Klaas
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.