user4506537
user4506537

Reputation:

What is the behaviour when we assign constant integer reference to a integer pointer in c++?

Please look into the below code. I assigned an address of a const integer value to an integer pointer. And i can able to print those addresses also, but i am not able to print the values(commented lines). Could anybody please explain what is actually happening here internally?

 int main()
  {
       int *a;
       cout<<a<<"\n";
       a = (int*)20;
       cout<<a<<"\n";
       cout<<(int*)20<<"\n";
       int *b;
       cout<<b<<"\n";
       b = (int*)20;
       cout<<b<<"\n";
       //cout<<*a<<"\n";
       //cout<<*b<<"\n";
       return 0;
}


Output:
-------
0
0x14
0x14
0x7fff3c914690
0x14

Upvotes: 1

Views: 53

Answers (2)

Rollen
Rollen

Reputation: 1210

You didn't assign the address of a const integer value. Instead what you said was, "Treat 20 as an address" i.e. (int*)20. So when you dereferenced it (i.e. *a) you were saying what is at address 20 which of course is garbage. You need to store 20 somewhere before getting the address of it.

const int value = 20;
const int * a = &value;
cout << *a << endl;

Would be fine...

Upvotes: 4

Emil Laine
Emil Laine

Reputation: 42828

Let's go through that line by line:

int *a;

This initializes a pointer to int with random data that happened to be in memory at the time.

cout<<a<<"\n";

Prints the memory address a holds, which is random because it wasn't initialized.

a = (int*)20;

Treats 20 as a memory address containing an int, and makes a point to that memory address (which again contains random junk data).

cout<<a<<"\n";

Outputs the address that a holds, which is 20.

cout<<(int*)20<<"\n";

Outputs 20 as a memory address.

int *b;
cout<<b<<"\n";
b = (int*)20;
cout<<b<<"\n";

Same as with a, see above.

cout<<*a<<"\n";
cout<<*b<<"\n";

These two would dereference the memory at address 20 which will result in undefined behavior.

In conclusion, this code doesn't make much sense.

Upvotes: 1

Related Questions