I am trying to change the value of a “static char *” I define at startup, I do it from inside a function, and when this function returns the var I am trying to re-set the value doesn’t retain it.
Example:
static char *X = "test_1";
void testFunc()
{
char buf[256];
// fill buf with stuff...
X = buf;
}
How can I achieve this without using static for buf? Should I use another datatype? if so, which one?
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*, usestrcpy(seeman strcpy) and make surebufgets NUL-terminated. strcpy will copy thebufinto the destinationX.I should add that there are more reasons to use
std::string. When usingstrcpy, 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 thanstrlen("test_1"), so you’ll have problems. There are ways around this reallocate X (like thisX = new char[number_of_characters_needed]). Or initializeXto a char array of 256 instead of achar*.IIRC,
strcpyto a static defined string literal (like char *X = “test_1”) is undefined behavior… the moral of the story is… It’s C++! Usestd::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)