gpt4 book ai didi

C++ const char* 指针赋值

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:47 24 4
gpt4 key购买 nike

我一定错过了一个明显的事实——有一段时间没有使用 C++ 编程了。为什么我不能在将它分配给 const char* 变量后打印 c 风格的字符串?但是如果我尝试直接打印它而不分配它就可以正常工作:

#include "boost/lexical_cast.hpp"

using namespace std;
using boost::lexical_cast;

int main (int argc, char** argv)
{
int aa=500;
cout << lexical_cast<string>(aa).c_str() << endl; // prints the string "500" fine

const char* bb = lexical_cast<string>(aa).c_str();
cout << bb << endl; // prints nothing

return EXIT_SUCCESS;
}

最佳答案

c_str 返回的 C String 只有在从中获取它的 std::string 存在时才可用。一旦 std::string 被销毁,C String 也将消失。 (此时,尝试使用 C 字符串会产生未定义的行为。)

其他操作也可能使 C 字符串无效。通常,任何修改字符串的操作都会使 c_str 返回的指针无效。

关于C++ const char* 指针赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14372689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com