c++ - 如何将一个 char* 分配给另一个 char*

标签 c++

这是我的第一个问题。

我有一段代码:

char* str1 = "yes" ;
char* str2 = "no" ;
*str1 = *str2;    //----crash

*str1 = *str2; //here program crashes.

当我可以对整数指针做同样的事情时,为什么不能对 char 指针做同样的事情。 请解释。

最佳答案

这个原始代码,

char* str1 = "yes" ;
char* str2 = "no" ;
*str1 = *str2;    //----crash

*str1 = *str2; //here program crashes.

... 无效,从 C++11 及更高版本开始不允许。我们现在处于 C++14,并且很可能会在短时间内达到 C++17。

C++11 编译器对此有何评价?例如,带有选项 -std=c++14 的 MinGW g++ 5.1.0 说了什么?

C:\my\forums\so\121> g++ foo.cpp
foo.cpp: In function 'int main()':
foo.cpp:3:18: error: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
     char* str1 = "yes" ;
                  ^
foo.cpp:4:18: error: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
     char* str2 = "no" ;
                  ^

C:\my\forums\so\121> _

However, Visual C++ 2015 update 2 erroneously accepts the code.

The reason why the implicit conversion to char* was dropped from the language was precisely that it's unsafe. It allows the code to attempt modification of the literals, as this code does. But the literals can be stored in read-only memory, which then can cause a crash (as it did for the OP), or other undesirable behavior. It's just Undefined Behavior, where anything can happen, including that the code appears to “work”.


How to fix it?

Use std::string.

Like this:

#include <string>
using namespace std;

auto main() -> int
{
    string str1 = "yes" ;
    string str2 = "no" ;
    str1 = str2;    // OK.
}

如果你绝对想使用通过指针处理的 C 级零终止字符串,也许是为了与某些 C 代码兼容,然后使用适合指针的 const,使用本地或动态分配适当存储数组,并使用 C 标准库的字符串函数,或者自己动手,它们是非常简单的函数:

#include <assert.h>
#include <string.h>     // The ".h" header is a C++ version of C's header.

auto main() -> int
{
    char str1[] = "yes" ;
    char const* const str2 = "no" ;

    int const n2 = strlen( str2 );
    assert( sizeof( str1 ) > n2 );
    strcpy( str1, str2 );
    assert( strcmp( str1, "no" ) == 0 );
}

关于c++ - 如何将一个 char* 分配给另一个 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371257/

相关文章:

c++ - ifstream.open() 不打开文件

c++ - 快速排序不排序 C++

c++ - 获取 istringstream 的未读部分

c++ - 错误 124 - SHFileOperation 的系统调用级别不正确

c++ - boost::thread undefined reference

c++ - 使用模板和继承的容器实现

c++ - 基于并行位操作的 openMP 素数查找器?

c++ - 获取 C++0x 随机数生成器状态的标准方法是什么?

c++ - 将 Gsoap Src 文件编译到我的项目中

c++ - cv::Scalar 类型是什么意思?