How to assign a string to char *pw in c++

For constant initialization you can simply use

const char *pw = "mypassword";

if the string is stored in a variable, and you need to make a copy of the string then you can use strcpy() function

char *pw = new char(strlen(myvariable) + 1);
strcpy(pw, myvariable);
// use of pw
delete [] pw; // do not forget to free allocated memory

If you just want to assign a string literal to pw, you can do it like char *pw = "Hello world";.

If you have a C++ std::string object, the value of which you want to assign to pw, you can do it like char *pw = some_string.c_str(). However, the value that pw points to will only be valid for the life time of some_string.


If you mean a std::string, you can get a pointer to a C-style string from it, by calling c_str. But the pointer needs to be const.

const char *pw = astr.c_str();

If pw points to a buffer you've previously allocated, you might instead want to copy the contents of a string into that buffer:

astr.copy(pw, lengthOfBuffer);

If you're starting with a string literal, it's already a pointer:

const char *pw = "Hello, world".

Notice the const again - string literals should not be modified, as they are compiled into your program.

But you'll have a better time generally if you use std::string everywhere:

std::string astr("Hello, world");

By the way, you need to include the right header:

#include <string>

Tags:

C++