Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Allocate Two Dimentional Array...

Status
Not open for further replies.

7496764

Programmer
May 25, 2002
6
0
0
IN
Hi Group,

I want to allocate two dimentional array.
How can i do it.

Suppose my variable is this

char **c;

i want to allocate it with new/malloc.

Thanx in advance.
 
Do it so:

char **c = NULL;
alloc_array(&c, 100, 200); //alloc it
free_array(c, 100); //free memory
c = NULL;

BOOL alloc_array(char ***c, int size1, int size2)
{
*c = new char*[size1];
if(*c == NULL) {
return FALSE;
}
for(int i = 0; i < size1; i++) {
(*c) = new char[size2];
if((*c) == NULL) {
return FALSE;
}
}
return TRUE;
}

void free_array(char **c, int size1)
{
if(c == NULL) {
return;
}
for(int i = 0; i < size1; i++) {
if(c != NULL) {
delete [] c;
}
}
return;
}
 
PS: I don't know way, but Tek-Tips server has changed my code. It should be so:

char **c = NULL;
alloc_array(&c, 100, 200); //alloc it
free_array(c, 100); //free memory
c = NULL;

BOOL alloc_array(char ***c, int size1, int size2)
{
*c = new char*[size1];
if(*c == NULL) {
return FALSE;
}
for(int x = 0; x < size1; x++) {
(*c)[x] = new char[size2];
if((*c)[x] == NULL) {
return FALSE;
}
}
return TRUE;
}

void free_array(char **c, int size1)
{
if(c == NULL) {
return;
}
for(int x = 0; x < size1;x++) {
if(c[x] != NULL) {
delete [] c[x];
}
}
delete [] c;
return;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top