请告诉我这个代码出了什么问题

please tell me whats wrong in this code

本文关键字:什么 问题 代码 告诉我      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
    char *fp = "Alex";
    cout<<fp <<" "<<(void*)fp<<endl;
    *(fp+1) = 'p';
    cout<<fp <<" "<<(void*)fp<<endl;
}

您修改了一个字符串文字。这是未定义的行为。

如果增加编译器的警告级别,则需要char *fp = "Alex";行出现警告/错误,因为它会创建一个指向不可变数据的非常数指针。它只允许在C++中与C兼容,这也是一个错误的特性。

我真的不喜欢回答这样的"问题",但这里有一个明显的错误:

*(fp+1) = 'p';

当您为fp分配字符串文字时,它指向只读内存。因此,您无法修改fp指向的内容。如果您想修改字符串,请将fp声明为char[],以便在堆栈上分配它。

我不得不假设您谈论的是以下编译器警告:

prog.cpp: In function ‘int main()’:
prog.cpp:5: warning: deprecated conversion from string constant to ‘char*’

下次请在问题中告诉我们为什么你认为有些事情"不对劲"。

正如警告所指出的,将字符串常量转换为char*在C中是很正常的,但在C++中是不赞成的。

改为:

#include <iostream>
using namespace std;
int main() {
    char const *fp = "Alex"; // <--- `const` here
    cout<<fp <<" "<<(void*)fp<<endl;
    *(fp+1) = 'p';
    cout<<fp <<" "<<(void*)fp<<endl;
}

然后您会发现您的语句*(fp+1) = 'p'没有编译。这是因为const;事实上,原始代码中缺少const只是隐藏了您可能无法修改字符串文字的底层数据的事实。

您应该将字符复制到程序拥有的新缓冲区中。您可以使用std::string:巧妙地做到这一点

#include <iostream>
#include <string>
using namespace std;
int main() {
    string fp = "Alex";
    cout << fp << " ";
    fp[1] = 'p';
    cout << fp << " ";
}

一般来说,尽可能使用std::string。很少有理由回避C++标准库的特性。