【发布时间】:2017-01-18 00:52:22
【问题描述】:
我有一个非常基本的问题,但我无法理解。 我想知道如何检索字符串中每个字符的内存地址。
例如:
string str("Test");
cout << size(str) << endl;
我知道这会返回这个 4,因为这个字符串是 4 个字节,但是我如何在屏幕上输出每个字节的内存地址?
我试过了
string s = "abcd";
string::iterator pos;
for (pos = s.begin(); pos != s.end(); ++pos) {
cout << &pos << endl;
}
cin.get();
return 0;
但这是输出:
00AFFB8C
00AFFB8C
00AFFB8C
00AFFB8C
但它不需要类似于:
00AFFB8C
00AFFB8D
00AFFB8E
00AFFB8F
那么有人知道我在这里做错了什么吗?
【问题讨论】:
-
您看到相同的地址,因为它们存储在同一个地方。
-
哦,错了。
size(str)返回std::string对象的大小,而不是std::string中文本的大小。尝试std::string::length()获取字符串的长度。 -
@ThomasMatthews -
std::size(c)返回c.size()。你好像在想sizeof。 -
&pos 是迭代器的地址,在栈上声明。 ++pos,不增加其地址。
标签: c++ string for-loop memory iterator