Allocating Arrays on the Free Store
I'm attempting to make a random name generator - for this I was going to pull in about a hundred names from a txt file into an array, and access the array using a random number. If this is a clumsy way of doing things and anyone has any better ideas, this would be really appreciated.
But the problem I'm having is that the array is of course an array of strings. Which makes it an array of arrays of chars. And when I try to create this on the free store, I can't keep track of the chars.
Here's the code I'm using to experiment:
Code:
char** array;
array = new char*[50];
char * s;
s=new char[20];
strcpy(s,"Lemmings.");
//doesn't like char s[20];
int e; //e will access the elements of 'array'. In each of these elements will be placed a string.
e=0;
for (e;e<5;e++){
strcat(s,"A");
//putting the string in the array.
*array+=e; //*array-the value pointed at by the array pointer- [0] is moved along to [e].
*array = new char[10]; //a new character pointer (ie, string) is created at array[e];
strcpy(*array,s); //copy the string s into the element (*array) of the array (array).
cout<< *array <<"end.\n"; //print the element (the line pointed to by array).
*array-=e; //array pointer moved back to array[0]
}
e=1;
*array+=e;
cout<<*array;
Now I'd expect the final line to print "LemmingsA", that being the string that was created at array[1]. But it just returns garble. And I don't know why.
Any help on this would be helpful.