Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

like...

char *pw = some string

??

like image 942
Anuya Avatar asked Feb 10 '10 08:02

Anuya


2 Answers

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
like image 196
sergiom Avatar answered Oct 18 '22 04:10

sergiom


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.

like image 41
Hans W Avatar answered Oct 18 '22 05:10

Hans W