tags:

views:

187

answers:

5

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

like...

char *pw = some string

??

+3  A: 

For constant initialization you can simply use

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
sergiom
You should use `const char *pw` on literals.
Notinlist
+1  A: 

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.

Hans W
It's only guranteed to be valid until you perform a mutating operation on `some_string` .
Bill
+1  A: 

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>
Daniel Earwicker
+1  A: 

String must be enclosed in double quotes like :

char *pStr = "stackoverflow";

It will store this string literal in the read only memory of the program. And later on modification to it may cause UB.

Ashish
if i use like char* pw = "some string"; i am getting exception. "corruption of heap" – karthik 4 secs ago edit [delete this comment]
Anuya
@Mac - your code works because of C compatibility but it's good practice to use a `const char *`
Manuel
+1  A: 

I think you may want to do this:

using namespace std;
string someString;
geline(cin,someString);
char *pw = strdup(someString.c_str());

But consider doing itanother way. Check out http://tiswww.case.edu/php/chet/readline/rltop.html (GNU Readline library). I don't know details about it, just heard about it. Others may have more detailed or other tips for reading passwords from standard input.

If you only want to use it for a single call for something you do not need to copy the contents of someString, you may use someString.c_str() directly if it is required as const char *.

You have to use delete[] on pw some time later,

Notinlist
`strdup` is handy but beware of portability issues: http://stackoverflow.com/questions/482375/c-strdup-function
Manuel