Converting a std::list to char*[size]

前端 未结 6 1252
温柔的废话
温柔的废话 2021-01-21 20:54

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

6条回答
  •  佛祖请我去吃肉
    2021-01-21 21:24

    You're right:

    for(list::iterator t=commandList.begin(); t!=commandList.end(); t++)
    {
        char item[strlen((*t).c_str())]; //create character string
    

    ...this does create an array, but it creates it on the stack, so when you reach the end of its scope, it gets destroyed.

        strcpy(item, (*t).c_str()); //convert from const char to char
        progArgs[count] = item;
        count++;
    }
    

    ...and this closing brace marks the end of its scope. That means you're creating a string, putting it into your array, then destroying it before you add the next one. Thanks to the fact that you're creating them all on the stack, each new one you create is being created in exactly the same place as the previous one, so it's no surprise that at the end of it all, you have a bunch of identical strings.

    Perhaps it would be better if you told us what you're trying to accomplish here, so we can help you do that.

提交回复
热议问题