How to change value or static char * to function? C ++

I am trying to change the value of "static char *" that I define at startup, I am doing this from within the function, and when this function returns var, I am trying to reset the value doesn’t save 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 a different data type? if so, which one?

+3
source share
3 answers

As James said, use std::string... except that the global order of construction and destruction is undefined between translation units.

, char*, strcpy (. man strcpy) , buf NUL-. strcpy buf X.

char buf[256];
// ...
strcpy(X, buf);

, std::string. strcpy , (X) . 256 , strlen("test_1"), . X (, X = new char[number_of_characters_needed]). X char 256 char*.

IIRC, strcpy (, char * X = "test_1" ) - undefined... ... ++! std::string!:)

( , ++, , , " undefined" , ... , )

+2

X = buf X, buf. , buf , .

C , std::string, std::string .

+6
static char *X = "test_1";

void testFunc()
{
    char buf[256];
    // fill buf with stuff...
    X = buf;
}

, , , X X = buf;

buf ( {}), . , , buf undefined, X buf ( ) .

, X - , . , , .

So, if you want to change the value of X, just attach whatever you want. Just be careful not to invalidate the data that it provides before you access data X (* X).

0
source

Source: https://habr.com/ru/post/1747637/


All Articles