2

I wanna do something like:

string result;
char* a[100];
a[0]=result;

it seems that result.c_str() has to be const char*. Is there any way to do this?

2
  • Transfer to const char* and then do a strcpy Commented Apr 24, 2013 at 4:34
  • 2
    This strikes me as a likely XY problem. Can you tell us what you're trying to accomplish by doing this? In most cases, instead of asking how to do this, you should be asking how to avoid doing this. Commented Apr 24, 2013 at 4:41

6 Answers 6

8

You can take the address of the first character in the string.

a[0] = &result[0];

This is guaranteed to work in C++11. (The internal string representation must be contiguous and null-terminated like a C-style string)

In C++03 these guarantees do not exist, but all common implementations will work.

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

2 Comments

I don't think it will compile unless a is declared const though (or unless you cast away const-ness)
2
string result;
char a[100] = {0};
strncpy(a, result.c_str(), sizeof(a) - 1);

Comments

2

There is a member function (method) called "copy" to have this done.

but you need create the buffer first.

like this

string result;
char* a[100];
a[0] = new char[result.length() + 1];
result.copy(a[0], result.length(), 0);
a[0][result.length()] = '\0';

(references: http://www.cplusplus.com/reference/string/basic_string/copy/ )

by the way, I wonder if you means

string result;
char a[100];

Comments

1

You can do:

char a[100];
::strncpy(a, result.c_str(), 100);

Be careful of null termination.

Comments

0

The old fashioned way:

#include <string.h>

a[0] = strdup(result.c_str());  // allocates memory for a new string and copies it over
[...]
free(a[0]);  // don't forget this or you leak memory!

Comments

0

If you really, truly can't avoid doing this, you shouldn't throw away all that C++ offers, and descend to using raw arrays and horrible functions like strncpy.

One reasonable possibility would be to copy the data from the string to a vector:

char const *temp = result.c_str();
std::vector<char> a(temp, temp+result.size()+1);

You can usually leave the data in the string though -- if you need a non-const pointer to the string's data, you can use &result[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.