for some reason I cannot explain, every single item in the character array…is equal to the last item added to it…for example progArgs[0] through progArgs[size] contains the value of the last item.
I cannot figure out what I’m doing wrong for the life of me. Any suggestions?
int count = 0;
char *progArgs[commandList.size()]
for(list<string>::iterator t=commandList.begin(); t!=commandList.end(); t++)
{
char item[strlen((*t).c_str())]; //create character string
strcpy(item, (*t).c_str()); //convert from const char to char
progArgs[count] = item;
count++;
}
edit:
Thanks for all the quick responses everyone…I see what you are talking about
You’re assigning the same pointer (the address of the first element of the stack array
item) to each element ofprogArgs, then repeatedly overwriting that memory. You can do:and get rid of the first two lines of the for body.
strdupallocates memory, so you will have to free each element withfreelater. Also, you were not allocating a character for the NUL-terminator. You need wouldstrlen+ 1. However, this is not an issue withstrdup, since it allocates for you.