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
progArgs
is an array of pointers to char.
You set each of these pointers to point to item
. item
is a local variable in the loop, so as soon as the loop exits, item
no longer exists and the pointers are no longer valid[*]. However, in your C++ implementation, they all still point to the bit of memory which used to be the array item
on the stack. This memory contains whatever it was last used for, which is the sequence of characters from the last string in the list.
If you want to copy a list of strings to an array, it would be better if possible to use an array of strings:
std::string progArgs[commandList.size()] // if your compiler has C99 VLAs as an extension
int count = 0;
for(std::list::iterator t=commandList.begin(); t != commandList.end(); ++t) {
progArgs[count] = *t;
++count;
}
Or even better, use a vector instead of an array:
std::vector progArgs(commandList.begin(), commandList.end());
[*] to be more precise, the scope of item
is a single repeat of the loop, it's nominally "created" and "destroyed" each time around. But this doesn't do any work - on your C++ implementation the same region of memory is re-used each time, and there's no work needed to create or destroy an array of char on the stack.