Dynamically allocated array of dynamically allocated arrays of characters

can someone please show me an example on how this looks ?!
how would my class's constructor look, if I use this ?!

Example:

1
2
3
4
5
6
7
8
9
10
class Test
{
private:
char** name;
int no;
public:
Test(int n=0, ....} // the constructor //
no=n;
...
};



How should my constructor look for the char** name.
I know I'd have to do something like name= new char[blabla]...
but the double char confused me..
Last edited on
You do not have to initialize the constructor.. if you want to the make allocation of the * name as
1
2
3
4
5
6
7
#define CONST 50 // Can be any number depending upon the size of the array you want to use 

name = new char*[CONST] ; 


for( int i = 0 ; i < size ; i++ ) 
 name [i] = new char[length of string] ;


please correct me if i am wrong ..

you have to take extra precaution while deleting two dimesional array .
Last edited on
To delete the array stick something like this in your constructor:
1
2
3
4
5
for(size_t i = 0; i < size; i++)
{
delete []name[i];
}
delete []name;


I also suggest taking a look at std::vector and std::string. Your "name" variable can be written in a much cleaner and safer way by doing the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
std::vector<std::string> name;
//This will create a "vector" object of "strings". The strings are basically character
//arrays but you don't need to worry about memory allocation and can do things 
//like this:
std::string mystring = "Hello World";
string1 = string2;
string1 += string2;
//You can even access individual characters:
string1[0] = 'H';
//A vector is basically a dynamic array, but it deletes and allocates memory for
//you. You can either reserve() space and use it like a normal array:
std::vector<int> vec;
vec.reserve(10);
vec[5] = 5;
//Or you can push/pop values at the end. This basically means sticking them onto 
//the end of the vector, or taking them back off:
std::vector<int> vec;
vec.push_back(5);
std::cout<< vec.back(); //Returns last object in vector.
//To get the size of the vector use vec.size() 

Here are the sites for vector and string:
http://www.cplusplus.com/reference/stl/vector/
http://www.cplusplus.com/reference/string/string/
And Disch's write-up on how evil Multi-Dimensional arrays are:
http://www.cplusplus.com/articles/G8hv0pDG/
Topic archived. No new replies allowed.