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.
Printable View
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;
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.
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