简体   繁体   中英

convert input string to char* <Bad Ptr>

the problem is my console application gets a string from user:

string input;
cin >> input;

Now I want to convert this string to char* and then pass it to a function:

char *argument = NULL;
argument = (char *) input.c_str();

my function is declared as :

int function (char *input, char *output)

I've got access violation when debug this code, so I tried to define everything:

strcpy(argument, input.c_str());

but again I've got access violation and Bad Ptr!! any clue?

Your problem is that c_str() returns a const char* , not a char* . You are not allowed to modify any characters in the character sequence returned by c_str().

So you need to:

const char *argument = input.c_str();

Your compiler would have caught this error if you didn't do the cast in:

argument = (char *) input.c_str();

Without the cast:

argument = input.c_str();

it would not have compiled (or perhaps it would have compiled, but with a big, fat warning attached to it).

Furthermore, if you later modify input , the pointer you got from c_str() is no longer valid and accessing it will also result in undefined behavior.

If you want to have a char* version of the string, then you should copy it:

char *argument = new char[input.length() + 1];
std::strcpy(argument, input.c_str());

Do not forget to free argument when you no longer need it:

delete[] argument;
argument = (char *) input.c_str(); 
           ^^^^^^^^ you don't need this. further c_str() returns a "const pointer to char"
                    not "pointer to char". 

int function (char *input, char *output)
             ^^^^^^^^^^^^|________ It should be "string input" or "string &input"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM