0

I have an array of strings that I would like to copy into a struct member for use in the program...

here is what i have as a string array declaration:

const char *stringArray[3] = {"my", "string", "array"};

How can I copy the data into a struct?

3
  • Modify the language tag, if it isn't C. Commented Mar 15, 2012 at 4:49
  • You're very vague about what you're trying to do. Do you want pointers to these strings in the struct, so you can access the strings but not modify them? Do you want copies in the struct so you can modify them? Do you need additional memory allocates so the struct can hold larger strings? Commented Mar 15, 2012 at 5:06
  • yes, I would like to point to the strings...I don't need to modify them/ Commented Mar 15, 2012 at 5:07

2 Answers 2

2
struct MyStruct {
  std::vector<std::string> strings;
};

MyStruct my_struct;
const char *stringArray[3] = {"my","string","array"};
for (int i=0; i!=3; ++i) {
  my_struct.strings.push_back(stringArray[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

1
struct foo {
   std::string fooStr;  // const std::string fooStr;
};

const char *stringArray[3] = {"my", "string", "array"};

foo obj;
obj.fooStr = stringArray[0];

If you don't wish to modify the member variables - then const qualify the member variable and do -

foo obj = { stringArray[0] };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.