首页 文章

将char数组转换为字符串并存储字符串?

提问于
浏览
-2

我想使用从char数组转换的字符串,但是当我编辑char数组时,字符串似乎发生了变化 . 我意识到两者都指向内存中的相同位置,并尝试将字符串存储在新字符串中 . 但是,当我编辑char数组时,即使它们具有不同的内存位置,新字符串仍然会更改 . 编辑原始数组时如何不更改新字符串?顺便说一句,我正在使用Dev C.

char str[] = "Test test";
string z(str);
string s = z;
printf("%s, str[]'s location = %d, z location = %d, s location = %d", s, str, z, &s);
str[0] = 'n';
printf("\n%s, str[]'s location = %d, z location = %d, s location = %d", s, str, z, &s);

1 回答

  • 3

    我想使用从char数组转换的字符串,但是当我编辑char数组时,字符串似乎发生了变化 .

    编辑char数组时,不会以任何方式修改std :: string .

    我意识到两者都指向同一个位置

    他们没有指向同一个位置 .

    并尝试将字符串存储在新字符串中 . 但是,当我编辑char数组时,新字符串仍然会更改

    另一个std :: string也没有被修改 .

    编辑原始数组时如何更改新字符串?

    就像你在例子中所做的那样: str[0] = 'n'; .


    您的问题是该程序具有未定义的行为 . printf 对给定的参数类型有严格的要求 . 您的计划不符合这些要求:

    "\n%s, str[]'s location = %d, z location = %d, s location = %d"
        ^                      ^                ^                ^
        |           %d requires that the argument is int. None of str, z, &s is int
        %s requires that the argument is char*. s is a std::string instead
    

    使用 std::cout 更容易显示字符串不会更改:

    char str[] = "Test test";
    string s(str);
    std::cout << s << '\n'; // prints Test test
    str[0] = 'n';
    std::cout << s << '\n'; // prints Test test
    

相关问题