c++ - 查找由链表链接的数据的各个地址。 C++

标签 c++ list pointers iterator memory-address

我在从位于链接列表中的项目中取回一些地址时遇到了一些麻烦。而不是在 for 循环开始时创建和初始化的迭代器地址,我想获取位于列表内的实际数据的地址。如果不创建我自己的列表实现,这可能吗?这是我已经得到的代码块,但显然它没有按照我想要的方式工作。

int j = 0;

testIntList.resize(100);
for (list<int>::iterator i = testIntList.begin(); i != testIntList.end(); ++i) {
    *i = j*j;
    int * k = &(*i);
    cout << "the value of the iterator is " << *i << " and the address of the iterator is " << &i << "and the address of the pointer is " << *k << endl;
    j++;
}

我以这种方式使用 k 来尝试获取内存中迭代器值地址的实际指针。非常感谢任何帮助。

最佳答案

i 是您的迭代器,因此 &i 将是迭代器的地址 - 而不是您想要的。现在,您知道 *i 是您的迭代器指向的对象,因此该对象的地址是 &*i。这就是您在 k 中输入的内容。只需打印出 k

cout << "the value of the iterator is " << *i
     << " and the address of the iterator is " << &i
     << " and the address of the pointer is " << k << endl;

关于c++ - 查找由链表链接的数据的各个地址。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15101375/

相关文章:

c - C 中转换为 (char*) 和 *(char**) 的区别(实现 malloc)

C++ - 整个程序持续时间的单个本地类实例

r - 缩写科学名称的功能

c++ - 索引数组快速排序调试

algorithm - 如何连接列表中具有相同值的字符串列表

python - 替换列表列表中的值

c++ - 为什么不专门化函数模板呢? (问答)

c - 如何访问 C 结构体中的指针成员?

c++ - Project Euler 18 - C++ 通过引用传递数组

android - 在 Windows 中为 android 编译 protobuf 2.6.1