How to declare double pointer dynamically?

usually how we initiaze the declared pointer. Say
1
2
 In header file : char* name;
In CPP file 	: name = new  char[length];


I need to do similar kind of dynamic declaration for double pointer. Say
In header file : char** names;

In CPP file :Initially i know only the count value. After that once i enter into a loop then only i know the lengths of each name on iteration. So here i want initialize "names" with count alone first like
1
2
3
4
5
6
7
names = char*[10];
for(int i=0;i< 10; i++)
{
	int len = array[i].getnamelength();
	names[i] = new char[len];
	strcpy(names[i],array[i]);
}

how can i initialize "names" dynamically?
Last edited on
Why aren't you using an array (vector) of strings?
Declare names like char * names[10];
Then it's pretty much what you did:

1
2
3
4
5
6
7
int len;
for(int i=0;i< 10; i++)
{
	len = array[i].getnamelength();
	names[i] = new char[len];
	strcpy(names[i],array[i]);
}

The above works if you don't know the size of each name but you know the number of names. If you don't know either you can do it like this:

Declare names like char ** names;
And then go:

1
2
3
4
5
6
7
8
9
10
11
12
int name_count;
//...
//get name_count somehow
//...
names=new char*[name_count];
int len;
for(int i=0;i< name_count; i++)
{
	len= array[i].getnamelength();
	names[i] = new char[len];
	strcpy(names[i],array[i]);
}

Last edited on
Why aren't you using an array (vector) of strings?
This is also a very good idea if you don't want to get dirty messing with pointers. But there are people who actually enjoy this...
Really shall wedo initialization like this
names=new char*[name_count];
Is it rightway?
Yes.
Topic archived. No new replies allowed.