optimizing a function to print words (in a sentence) in reverse order

Hi,

The program below tokenizes the string represented by s1 and copies each word in an array of pointers to char and prints each word in reverse order. It works perfectly fine. I am trying to optimize it. The way I've declared array of pointers is static (array of 10 pointers). And if the string s1 has just 2 words as shown below, then there will be wastage of 8 pointers. I don't want to do that. Is there a way to dynamically store each word in a pointer?


int strtok()
{
char s1[]="hello world";
char *token;
char *array[10];
int count = 0;

token=strtok(s1, " -,.");
if(token)
{
array[count] = new char[strlen(token)+1];
cout << endl << sizeof(array[count]) << endl;
strcpy(array[count],token);
}
while (token!=NULL)
{
cout << token << endl;
token=strtok(NULL, " -,.");
if (token)
{
count++;
array[count] = new char[strlen(token)+1];
strcpy(array[count],token);
}
}



for (int x=count; x >=0; x--)
{
cout << array[x] << " ";
}

return 0;
}
Use an STL container such as vector or deque.
Thanks Jsmith,

So there is no other way without using the STLs?
You can make the array dynamic, but that would be reinventing vector. vector is easier to use and get right than managing the memory yourself. If you have to manage the memory yourself (ie, homework), then you need

1
2
size_t  numWords = 0;
char** pWordArray = new char*[ numWords ];


Then any time you need to insert, you have to create a complete copy:

1
2
3
4
5
6
++numWords;
char** pNewArray = new char*[ numWords ];
// copy all words from pWordArray to this one;
// add the new word to the end;
// free all the memory associated with pWordArray;
pWordArray = pNewArray;

Thanks for this answer!
Topic archived. No new replies allowed.