How can I change the value or a static char* from a function? C++
I am trying to change the va开发者_如何学JAVAlue 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?
The line X = buf
sets the pointer X
to point to the first element of the array buf
. When the function returns, buf
goes out of scope and can no longer be used, so the pointer is useless at that point.
Unless you have specific reason to use raw C strings in your program, use the std::string
container, then you can simply return a std::string
and not worry about dynamically allocating and managing the memory for the string yourself.
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)
static char *X = "test_1";
void testFunc()
{
char buf[256];
// fill buf with stuff...
X = buf;
}
On the example above if you run and debug the code, you will see that the value of X will be changed on the line X = buf;
Once buf is not static and is defined inside a specific scope (between { }), it will be allocated as a temporary stack variable. Whenever the instruction pointer leaves that scope, buf becomes undefined, but X keeps the old buf address (pointing to a stack address) with a not valid data.
Notice that X is just a pointer, so you can change it anytime you want. And considering that it is static, its definition will be kept valid up to the end of the program.
So, if you want to change X value just atrib it anything you want. Just be careful to not invalidate the data it will point before you access X data (*X).
精彩评论