查找链接列表链接的数据的各个地址。 C ++

时间:2013-02-26 23:17:48

标签: 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来尝试获取迭代器值的地址内存中的实际指针。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

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;