在单独的函数中修改指向字符串文字的指针 [英] Modifying pointer to string literal in separate function

查看:65
本文介绍了在单独的函数中修改指向字符串文字的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个琐碎的问题,有人可以用比我已经遇到的更简单的方式向我解释.

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

C ++之旅(第二版)

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

使用g ++进行编译时,我得到

When using g++ to compile, I get a

警告:ISO C ++禁止将字符串常量转换为char *

Warning: ISO C++ forbids converting a string constant to char*

显然g ++是将* p自动转换为const吗?当然,我缺少一些基本的知识,但是我以前的搜索引擎和Google搜索使我离答案越来越近了.谢谢您的回复!

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!

下面都是两个很好的例子.谢谢大家的回答,非常有帮助!

Both great examples below. Thank you everyone for your responses, very helpful!

推荐答案

显然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.

这篇关于在单独的函数中修改指向字符串文字的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆