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

时间:2018-01-25 15:48:38

标签: c++ arrays string dev-c++

我想使用从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 个答案:

答案 0 :(得分: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
相关问题