It looks like you're having some trouble with arrays. As Brian pointed out, array indices start at 0 not 1. Thus your two strings
are string_array[0]
and string_array[1]
, not string_array[1]
and string_array[2]
.
Also, if your function takes a parameter const char* cstring_array
, then your variable char* cstring_array[2]
is probably not what you want. If you were to pass it in as is, you would essentially be passing in a char**
, not a char*
, as you can consider the name of an array to be equivalent to a pointer to its first element.
As you've presented your question, you could do something like the following (correcting for the indexing error, and assuming the function you mentioned is called myFunction
):
...
cstring_array[0] = string_array[0].c_str( );
cstring_array[1] = string_array[1].c_str( );
myFunction (cstring_array[0]);
myFunction (cstring_array[1]);
...
However, a simpler equivalent that doesn't require cstring_array
at all is:
...
myFunction (string_array[0].c_str( ));
myFunction (string_array[1].c_str( ));
...
Or, if your intention was to pass a single char
array containing both strings (which is a possibility from my interpretation of the question), then what you really mean you want to do is you want to produce a single string being the concatenation of your original two:
...
std::string str = string_array[0] + string_array[1];
myFunction (str.c_str( ));
...
Hope that helps!
EDIT: given the comments that have appeared since I wrote this, I'd say the first example is close to what you need. I'd do the following (where N is the number of entries in either array):
...
for (int i = 0; i < N; i++)
cstring_array[i] = string_array[i].c_str( );
myFunction (cstring_array);
...
This is the only approach possible. There is no standard function (AFAIK) that, given an array of string
will give an array of char*
. I suspect the reasons are that:
- It's not something that needs to be done often, so there's little call for such a function to be widely available.
- If there were such a function, it would most likely be very similar to the above anyway, in which case it's so trivial as to be unnecessary.
Basically, to answer your question, I don't think there is any more efficient method, and even if there were a standard library function to do this it would use this approach anyway.