allocating memory for char* array
A few questions.
I know how to allocate memory for say 5 words that contain 10 characters each.
say:
char* wrdArray[5];
for (int count = 0; count < 5; count ++)
{
wrdArray[count] = new char[10];
}
strcpy(wrdArray[0], "Here is the first string.");
cout << wrdArray[0];
..
.. etc.
but how can i allocate memory/is it possible? for predefined words
that are of different lengths
using:
char** wrd = { "..", ".. " }; // can i use this ?? how ??
char* wrd[5] = { "these", "words", " need", "memory", "???" };
if in the second case, do i have to allocate memory?, how would i go about it?, do i have to use a for loop and allocate memory individually, can i do a group allocate/deallocate?
such as:
free(wrd);
any ideas would be great.
thanks.
Re: allocating memory for char* array
Code:
char* wrdArray[5];
for (int count = 0; count < 5; count ++)
{
wrdArray[count] = new char[10];
}
strcpy(wrdArray[0], "Here is the first string."); //Bufferoverflow
Code:
char* wrd[5] = { "these", "words", " need", "memory", "???" };
There is a const missing.
Code:
const char* wrd[5] = { "these", "words", " need", "memory", "???" };
Fine.Now you have an array of 5 constant char pointer,with memory allocated by the compiler,so don't call free on it.
You can copy the array
Code:
char *myWrds[5];
for(int i = 0;i < 5;i++)
{
myWords[i] = new char[strlen(wrd[i]) + 1];
strcpy(myWrds[i],wrd[i]);
}