0

I need a way to convert multiple strings into the same char array. For example if I have

string str1;
string str2;
char *myArray = new char[str1.size() + str2.size() + 1];

What's the best way to add the string characters into myArray?

2
  • char myArray[str1.size() + str2.size() + 1] is not ok, but look for strcpy and strcat Commented Mar 18, 2015 at 17:41
  • Edited using dynamic memory instead. Thanks. Commented Mar 18, 2015 at 17:57

3 Answers 3

4

You could use another string to combine the two:

auto myArray = str1 + str2;

You can then access the underlying (constant!) char array with the .c_str method or, if you want to modify certain characters, access them with the operator[] on string.

If you need an actual, modifiable char* style array, use std::vector:

std::vector<char> myArray (str1.begin(), str1.end());
myArray.insert(myArray.end(), str2.begin(), str2.end());
myArray.push_back('\0');  // If the array should be zero terminated

You can then access the underlying, modifiable char array with the .data method.

Note that variable length arrays like char myArray[str1.size() + str2.size() + 1] are a compiler extension that only works on certain compilers. They are not standard C++.

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

1 Comment

I like this one. It's idiomatic.
2
strcpy(myarray,(str1+str2).c_str())

or

strncpy(myarray,(str1+str2).c_str(),(str1+str2).length())

2 Comments

Though I would use strncpy.
It's safer to use strncpy though.
0

use strcpy and strcat:

strcpy(myArray,str1.c_str());
strcat(myArray,str2.c_str());

although , the expression char myArray[str1.size() + str2.size() + 1] will not compile under C++ , since VLAs are forbidden , use dynamic memory allocation:

char* myArray = new char[str1.size() + str2.size() + 1]

1 Comment

But you know that a char array isn´t a class?

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.