std::string 每个字符的地址
我尝试打印 std::string
每个字符的地址。但我不明白 std::string
内部发生了什么,导致了这个输出,而对于数组,它给出了我预期的地址。有人可以解释一下发生了什么事吗?
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "Hello";
int a[] = {1,2,3,4,5};
for( int i=0; i<str.length(); ++i )
cout << &str[i] << endl;
cout << "**************" << endl;
for( int i=0; i<5; ++i )
cout << &a[i] << endl;
return 0;
}
输出:
Hello
ello
llo
lo
o
**************
0x7fff5fbff950
0x7fff5fbff954
0x7fff5fbff958
0x7fff5fbff95c
0x7fff5fbff960
I tried to print the address of each character of std::string
. But I amn't understanding what is happening internally with std::string
that is resulting this output while for the array it is giving the address as I expected. Could someone please explain what is going on?
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "Hello";
int a[] = {1,2,3,4,5};
for( int i=0; i<str.length(); ++i )
cout << &str[i] << endl;
cout << "**************" << endl;
for( int i=0; i<5; ++i )
cout << &a[i] << endl;
return 0;
}
Output:
Hello
ello
llo
lo
o
**************
0x7fff5fbff950
0x7fff5fbff954
0x7fff5fbff958
0x7fff5fbff95c
0x7fff5fbff960
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当
std::ostream
尝试打印char*
时,它假定它是 C 样式字符串。在打印之前将其转换为
void*
,您将得到您所期望的结果:When a
std::ostream
tries to print achar*
it assumes it's a C-style string.Cast it to a
void*
before printing and you will get what you expect:或者你可以使用旧的 printf
or you may use the old printf