问题
I have what is hopefully a trivial question that someone can explain to me in simpler terms than what I have already come across. While working through
A Tour of C++ (Second Edition)
I've been trying a few examples.
I'm currently trying to modify a pointer to a string literal in a separate function (I thought it would be easy.....).
using namespace std;
void test(char *ptr)
{
ptr = "test";
}
int main()
{
char *p = "abc";
test(p);
cout << p << "\n";
return 0;
}
When using g++ to compile, I get a
Warning: ISO C++ forbids converting a string constant to char*
Apparently g++ is auto-converting *p to a const? Surely I'm missing something basic, but my previous SO and google searches have gotten me no closer to the answer. Thank you for your responses!
EDIT: Both great examples below. Thank you everyone for your responses, very helpful!
回答1:
Apparently g++ is auto-converting *p to a const?
Quite the opposite. The string "abc"
will be in your binary, and that is supposed to be readonly for your program. Therefore, that string should only be read, and the value you get when assigning the string literal in this situation is of type const char*
. You get the error because you're assigning it to a non-const char*
. Try this instead:
const char *p = "abc";
Also, you'll have to change the function, too:
void test(const char *ptr)
{
ptr = "test";
}
It's still going to print abc
, however. That's because you're only modifying a copy of the value that you're passing. But C++ lets you pass a reference instead, which you can do like this:
void test(const char *&ptr)
{
ptr = "test";
}
Now that's a reference to a pointer pointing to a const char
... whew! Both the "abc"
and "test"
will be in the program's binary when it is compiled. When the program is run, the address of "abc"
is assigned to char *p
, and then the function to change it to have the address of "test"
instead is called. The &
tells it to work with the actual char *p
and not just a copy of it that gets lost when the function finishes.
回答2:
There are two things that can be const
; the pointer (char * const
), or the object (const char *
).
The string literal is const
, that's what the compiler is complaining about. You should use
const char *p = "abc";
The function would still not modify the pointer p
from main()
though, because it is passed by value to the function.
This should modify the pointer:
using namespace std;
const char * str2 = "test";
void test(const char *& ptr)
{
ptr = str2;
}
int main()
{
const char *p = "abc";
test(p);
cout << p << "\n";
return 0;
}
live demo
来源:https://stackoverflow.com/questions/52760524/modifying-pointer-to-string-literal-in-separate-function