0

I have some C+ arrays that I have built as follows:

std:array<const char *, 4) test1 = {abc.c_str(), def.c_str(), ghi.c_str()}; 

where abc, def, ghi are std::string

I have to pass this array to another function which has the following prototype: (int argc, char * argv[])

How should I modify array so that give non-const char* ot me that can be passed to above function. Or should I modify the function to const char*. I am not sure if the function tries to modify char* somewhere since this function code is not mine and not available as well currently.
But, in any case it would be good to ask how would I pass non-const char* array to the above function?

2 Answers 2

2

If there is a possibility that the function will modify the string, you should resize the string to the maximum size that the function might use then resize it again on return.

abc.resize(max); DoSomething(&abc[0]); abc.resize(strlen(&abc[0])); 

If you know for a fact that the function does not modify the string, then the function prototype is lying to you. You can lie back:

DoSomething(const_cast<char *>(abc.c_str())); 
Sign up to request clarification or add additional context in comments.

5 Comments

Scumbag function prototypes. That really is the only justified use for that I know of: making up for other people's mistakes. Good point with resizing the string too.
a main-style function can't increase the length of the strings passed in as arguments, even if it does modify them (it could, for example, use strtok)
@BenVoigt, a main-style function wouldn't receive strings it would receive char *s. I suppose if you know that the string length isn't going to change you could dispense with the pair of resize.
@harper: Did you intend to direct that comment to Mark?
@BenVoigt, since it's my answer I get notified either way. The comparison to main doesn't change my answer.
1

This should work

abc.append(1, 0); // guarantee NUL termination def.append(1, 0); ghi.append(1, 0); std:array<char *, 4> test1 = {abc.data(), def.data(), ghi.data()}; 

or

abc.append(1, 0); def.append(1, 0); ghi.append(1, 0); std:array<char *, 4> test1 = {&abc[0], &def[0], &ghi[0]}; 

4 Comments

+ strdup()/free() in case the prototyped function modifies the strings.
If you don't mind me asking, what's the point of abc.c_str(); etc? What side effects does it have?
@chris: It ensures that the string content is followed by a NUL byte.
@Alex: std::string is not immutable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.