As James said, use std::string
... except be aware that global construction and destruction order is undefined between translation units.
So, if you still want to use char*
, use strcpy
(see man strcpy
) and make sure buf
gets NUL-terminated. strcpy will copy the buf
into the destination X
.
char buf[256];
// ...
strcpy(X, buf);
I should add that there are more reasons to use std::string
. When using strcpy
, you need to make sure that the destination buffer (X
) has enough memory to receive the source buffer. In this case, 256 is much larger than strlen("test_1")
, so you'll have problems. There are ways around this reallocate X (like this X = new char[number_of_characters_needed]
). Or initialize X
to a char array of 256 instead of a char*
.
IIRC, strcpy
to a static defined string literal (like char *X = "test_1") is undefined behavior... the moral of the story is... It's C++! Use std::string
! :)
(You said you were new to c++, so you may not have heard "undefined behavior" means the computer can punch you in the face... it usually means your program will crash)