【发布时间】:2018-07-04 22:29:44
【问题描述】:
我想使用从 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);
【问题讨论】:
-
你用的是什么编译器?
-
你打印的东西不正确,你的警告应该告诉你。阅读
printf的手册,或者最好使用cout。 -
使用 cout,而不是 printf。你已经用错了!
-
%d用于打印整数值,std::string无法解析为使用printf()进行格式化。你为什么要使用printf()将控制台输出到 C++ 中?请改用std::cout。 -
@TheDude 好吧,OP 可以使用
.c_str()。