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

时间:2014-07-30 18:50:56

标签: c++ pointers const

我对C ++中的const指针感到困惑,并编写了一个小应用程序来查看输出结果。我正在尝试(我相信)添加指向字符串的指针,这应该不能正常工作,但是当我运行程序时,我正确地得到了#34; 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;
}

3 个答案:

答案 0 :(得分:4)

变量sappend函数内是本地的。一旦append函数返回该变量被破坏,就会留下指向不再存在的字符串的指针。使用此指针将转到undefined behavior

我向您提示如何解决此问题:一直使用std::string

答案 1 :(得分:0)

您正在向const char*添加std::string指针,这是可能的(请参阅this reference)。在char*类型(C样式字符串)上进行该操作是不可能的。

但是,您正在返回一个指向局部变量的指针,因此一旦函数append返回并弹出堆栈,返回的指针所指向的字符串将不存在。这会导致不确定的行为。

答案 2 :(得分:0)

类std :: string为operator +=类型的操作数重载了const char *

basic_string& operator+=(const charT* s);

实际上,它只是将此指针指向的字符串附加到std :: string类型的对象的内容中,如果需要,还可以分配额外的内存。例如,内部重载运算符可以使用标准C函数strcat 从概念上讲,它类似于以下代码段。

char s[12] = "Hello ";
const char *s2 = "World";

std::strcat( s, s2 );

考虑到您的程序有未定义的行为,因为在退出函数append后销毁本地对象后total将无效。所以主要的下一个状态

printf("%s", total);

会导致未定义的行为。