Ishan Jawade
Ishan Jawade

Reputation: 21

Why my pointer variable is holding different address and still pointing to variable successfully?

Code:

# include <iostream>
using namespace std;

int main(){
    int num = 10, *p;
    *p = num;
    cout<<" &num = "<<&num<<" p = "<<p<<endl<<" *p = "<<*p<<endl;
    return 0;
}

Output:

&num = 0x7ffeef0908c8 p = 0x7ffeef0908e0
 *p = 10

Theoretically content of 'p' is equal to the address of 'num'. But it's not happening here. But still, it's pointing 'num' successfully. Why?

Upvotes: 1

Views: 58

Answers (1)

Christophe
Christophe

Reputation: 73376

Your code is UB. It may look as if it worked, but could as well corrupt or crash the system, or anything else (usually bad) could happen.

 int num = 10, *p; // this leaves p unitialized; you don't know to what it points
 *p = num;         // OUCH!  This is UB because you dereference an unitialized pointer

Here a working alternative:

#include <iostream>
using namespace std;
int main(){
    int num = 10, *p;
    p = &num;    // make the pointer point to to num using the address
    cout<<"&num = "<<&num<<" num = "<<num<<" p = "<<p<<" *p = "<<*p<<endl;
    *p = 77;     // change the value pointed to
    cout<<"&num = "<<&num<<" num = "<<num<<" p = "<<p<<" *p = "<<*p<<endl;
    return 0;
}

Upvotes: 3

Related Questions