将字符串作为指针传递时出错,无法将const char *分配给char *

0 c++ string pointers char

我正在从一本教科书中学习C ++(《 C ++:初学者指南》,第二版,Herbert Schildt)。以下程序代码摘自本书,但错误,请有人向我解释为什么不允许这样做吗?

目的是演示一个指针作为参数:

#include <iostream>

using namespace std;

char *get_substr(char *sub, char *str); //function prototype

int main()
{
    char *substr;
    substr = get_substr("three", "one two three four");

    cout << "substring found: " << substr;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我不会列出函数体,因为它按预期运行,但是即使它仅返回零,也会导致以下错误:类型为“ const char *”的E0167参数与类型为“ char *”的参数不兼容,引用函数调用。我的理解是,无论如何,字符串基本上是C中char的数组,为什么不允许这样做,什么是合适的替代方法?先感谢您。

Mat*_*her 6

您的书已经过时了,不再符合标准了,因为从C ++ 11开始,char*乱七八糟了const

const char *get_substr(const char *sub, const char *str);
Run Code Online (Sandbox Code Playgroud)

看一下精选的C ++书籍清单

  • 感谢您的快速答复,我将确保对我的学习资料进行更彻底的审查。 (2认同)