gpt4 book ai didi

c++ - 在 C++ 中添加指向字符串的指针

转载 作者:行者123 更新时间:2023-11-27 23:03:56 24 4
gpt4 key购买 nike

我对 C++ 中的 const 指针感到困惑,并编写了一个小应用程序来查看输出结果。我正在尝试(我相信)添加一个指向字符串的指针,这应该无法正常工作,但是当我运行该程序时,我正确地得到了“hello world”。谁能帮我弄清楚这条线 (s += s2) 是如何工作的?

我的代码:

#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

const char* append(const char* s1, const char* s2){
std::string s(s1); //this will copy the characters in s1
s += s2; //add s and s2, store the result in s (shouldn't work?)
return s.c_str(); //return result to be printed
}

int main() {
const char* total = append("hello", "world");
printf("%s", total);
return 0;
}

最佳答案

s 变量在 append 函数内部。一旦 append 函数返回,该变量就会被破坏,留下一个指向不再存在的字符串的指针。使用此指针会导致 undefined behavior .

关于如何解决此问题的提示:使用 std::string一路走好!

关于c++ - 在 C++ 中添加指向字符串的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25044658/

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