mardi 6 octobre 2020

Pointers when reassigned still points to old value

Here, two variables a=1,b=2 and three pointer variables *p2a = &a , *q2p = p2a , *r2b = &b . When I change *p2a to point to *r2b, then pointer *q2p which is pointing to *p2a should also change right? . But *q2p still points to old value pointed by *p2q and not the new value of newly pointed *p2q which is the value of b pointed by *r2b.

#include <iostream>
using namespace std;

int main() {
    int a = 1;
    int b = 2;
    int* p2a = &a;
    int* q2p = p2a;
    int* r2b = &b;

    p2a = r2b;
    cout << *q2p;
    return 0;
}

Output:

1

My understanding of pointers is not that good. So If my question is really dumb I'm sry for it.

If you feel hard to get the problem description, then simply my question is, Why *q2p value is not changed when *p2q is changed to point to *r2b, but still *q2p pointing to old value of *p2q.

Aucun commentaire:

Enregistrer un commentaire