c++ - “一个指针指向某对象,同时另一个指针指向另外对象的下一地址,两个指针可能相等”是怎么回事?
高洛峰
高洛峰 2017-04-17 13:48:47
0
3
900

《C++ Primer》第五版,中文版。p50。
需要注意的是,一个指针指向某对象,同时另一个指针指向另外对象的下一地址,此时也有可能出现这两个指针值相同的情况,即指针相等。

之前在 CSDN 问答上问的:http://ask.csdn.net/questions/256146
“另外对象的下一地址”指的是不是尾后迭代器?
有人提到是相邻的导致相等。是否是下面的代码表达的意思:

#include <iostream>
#include <iterator>

using namespace std;

int a[] = { 1,2 };
int i = 4;

int main()
{

    int *p = end(a);
    if (p == &i) cout << "equ" << endl;

    return 0;
}
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
巴扎黑

Regarding your question, I don’t know if I understand the meaning of the description correctly. Look at the picture below

This is very simple, it is possible to be equal. When object C and object B are one object, they are equal.
I’ll lend you the code

#include <iostream>
#include <iterator>

using namespace std;

int a[] = { 1,2 };

int main()
{
    int* p1 = &a[1];        //指针p1指向对象a[1]
    int* p2 = &a[0] + 1;    //指针p2指向对象a[0]的下一个
    if(p1 == p2){
        cout<<"p1("<<p1 <<") = p2("<<p2<<")\n";
    }
    return 0;
}
PHPzhong

a-b-c-d-....
p1=b;
p2=a->next;

p1==p2

大家讲道理

因为内存是连续的, after the file pointer p completes traversing the array, it actually points to a memory address behind the array. The next memory address happens to be the address of i. So they are exactly equal. I think the following two pictures will solve your doubts:

Calculate the memory address yourself, an integer is 4 bytes. Did it happen to correspond?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template