且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在单独的函数中修改指向字符串文字的指针

更新时间:2023-11-10 08:40:22

显然g ++是将* p自动转换为const吗?

Apparently g++ is auto-converting *p to a const?

恰恰相反.字符串"abc" 将在您的二进制文件中,并且对于您的程序应该是只读的.因此,仅应读取该字符串,并且在这种情况下分配字符串文字时所获得的值的类型为 const char * .之所以会收到错误,是因为您正在将其分配给非常量 char * .尝试以下方法:

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";
}

但是,它仍将打印 abc .这是因为您只修改了要传递的值的副本.但是C ++可以让您传递引用,您可以像这样:

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";
}

现在,这是对指向 const char 的指针的引用.编译时,"abc" "test" 都将位于程序的二进制文件中.运行程序时,将"abc" 的地址分配给 char * p ,然后将其更改为具有"test的地址的函数"而是被调用.& 告诉它可以与实际的 char * p 一起使用,而不仅仅是在功能完成时丢失的副本.

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.