-12
class Tool { public: Tool(); ~Tool(); private: char **s; }; char *s1[]={"hello","world"}; 

How can I initialize s and make it same as s1?

s={"hello","world"} 

doesn't seem to work.

7
  • 1
    @Anguslilei char **s; this isn't a 2D array, this is a pointer to a pointer. Commented Apr 1, 2015 at 12:53
  • A total guess, std::vector<std::string>> Commented Apr 1, 2015 at 13:02
  • You never should. You should use a vector of strings. Commented Apr 1, 2015 at 13:04
  • What if I don't want to use vector, Is there any way that I could declare s in class Tool. Thank you all! Commented Apr 1, 2015 at 13:27
  • When you say you don't want to use a vector, is there a particular reason you don't want to? Strings will be much easier to manage in a vector as compared to a array of pointers to string arrays, so unless you have an incredibly good reason to not use a vector, you should do that. Commented Apr 1, 2015 at 13:36

1 Answer 1

1

While you could use a std::vector<std::string>, I feel it's more beneficial to you to directly answer your question.

char** s is a pointer to a pointer; possibly a pointer to the first pointer in an array of pointers.

char* s1[] is an array of pointers to const data (and should have actually been made const).

If you want s to work similarly to s1, you first need to allocate the array of pointers, which is the reason std::vector was recommended by others. You could do it yourself with new, but you have to release the allocated memory at some point. Using new directly is prone to leaks. std::vector will release its allocated memory when the object is destructed. You too could call delete[] in your destructor if you wanted to.

When your array has been allocated, you then need to std::copy the array of pointers in s1 to the array of pointers in s. It's not a single assign operation.

Sign up to request clarification or add additional context in comments.

2 Comments

It seems hard for s working similarly to s1. Now, I know the difference between s and s1 and thank you all guys very much!
And therein lies the reason others recommended std::vector<std::string> :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.