Search code examples
c++statictypesredefine

How can I change the value or a static char* from a function? C++


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?


Solution

  • 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)