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

前端 未结 6 1315
温柔的废话
温柔的废话 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:11

    item has scope local to the loop. The propArgs array therefore contains a bunch of stack-based pointers, likely all the same. You can examine how this works in the debugger, just step thru the loop twice and it should be clear what's going on.

    By the time you exit the loop, the buffer addressed by the common pointer contains the most recently-copied c_str().

    You could fix this by doing

    char* item = new char[strlen((*t).c_str()) + 1];
    

    but then you'd have to delete[] all the propArgs array entries when you exit the loop.

    This code shows a fundamental lack of understanding of memory management such that further reading might be useful before restructuring the code. If the code used here was in only slightly more complex context than this example, it might just crash since any access of propArgs outside the loop would rely on an invalid (no longer in scope) item.

提交回复
热议问题