请告诉我这个代码出了什么问题
please tell me whats wrong in this code
#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++标准库的特性。
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了