I have:
vector<string> myVector = {0};
myVector.push_back("first");
myVector.push_back("second");
char *list[] = ????
I want it to be initialized like if I was doing this
char *list[] = { "first", "second", NULL };
I know I can start allocating memory based on the size and of the vector and the size of the longest string in the vector (list[v.size()+1][longest_string_in_vector]
) but I wanted to see I'm not thinking of something that might be easier/faster.
If the legacy code requires a
char **
, then to create a variable list, you can create a vector as you initially are doing in your question.After that, create a
std::vector<char *>
, where the pointers are pointers within the vector for each item. Of course, you have to ensure that the vector doesn't go out of scope or is resized. It has to be fully "set up" before creating thestd::vector<char *>
.In addition, since you are certain that the legacy function does not attempt to alter the strings sent to it, we should take away the "constness" of the strings.
Basically, we created the strings in a vector, and created another vector that stores pointers to the strings.
Note that the function
legacy_function
takes achar **
, and all we need to do is pass it the address of the first element in our pointer vector.Live Example: http://ideone.com/77oNns
Edit: Rather than having the code strewn in different areas of your program, a better approach in terms of code organization is to encapsulate the creation of the array:
Live Example: http://coliru.stacked-crooked.com/a/834afa665f054a1f