On 21 Jun, 23:16, John Harrison <john_androni...@hotmail.comwrote:
JoeC wrote:
I have a simple question, how do I move data from a string to a
pointer array. I am doing some work in win32 and many of the commands
need pointers but poitner are cumbersome and I try to avoid them.
Basically I want to do:
char * prt;
std::string str;
str = "Hello";
ptr = str;
Not possible, but this is possible, using const is the vital difference
const char * ptr;
std::string str;
str = "Hello";
ptr = str.c_str(); // use c_str to get a *const* pointer
If you really want a non-const pointer (i.e. you want to use the pointer
to modify the string) then you are going to have to look elsewhere,
vector<charmight be what you need.
There is one situation where the const issue can be bypassed (and I
suspect it may come up with the Windows API).
To the OP:
As John says, you can't do
char* ptr = str.c_str();
but you can do
const char* ptr = str.c_str();
You can also do
char* ptr = const_cast<char*>( str.c_str() );
However, while you have bludgeoned the compiler into giving you a
pointer to non-cost char, you can't actually use that pointer to
modify data in the string. So the question is, why would you do this.
Answer: in your own code there's not likely to be any reason at all to
do this. But using some third party API you might find yourself faced
with needing to call functions like this
void some_API_function(char* c)
{
/*
This function doesn't actually modify the data pointed to by c. The
parameter should be const char* c but, for whatever reason, the const
has been left out[*].
*/
}
If you are *absolutely certain* that some_API_function really will not
ever, under any circumstances, modify the data pointed to by its
parameter, you can safely call it as below, allowing you to use
std::string within your own code.
some_API_function( const_cast<char*>(str.c_str()) );
[*] Reasons the const might have been left out:
1. The API is old enough to predate the widespread use of const.
2. The API is designed to be available to C and C++ programs. C did
not originally have const at all.
3. Carelessness on the part of the programmer who wrote the API.
Gavin Deane