Why we can't assign value to pointer

1.5k Views Asked by At

Memory addresses are often displayed in hex formate like 0x7ffff3a9ae94. Why we can't directly assign these values to pointers?

int *ptr=7ffff3a9ae94;

A "similar" behavior was shown when i tried this.(This might be a separate question itself)

int i=0;
*ptr=&i;
&i=ptr;

Both cases show syntax errors on g++ 4.7.2 which, i assume means its a language restriction.

Why this restriction is implemented in C++?

Or is this some kind of OS limitation?

Note: This question have similar title but it doesn't provide me answer to my question.

1

There are 1 best solutions below

1
On

there is no such rule , this :

int *ptr=(int*)0x7ffff3a9ae94;

compiles fine. although it's a bad thing to to.

intresting fact : the idea that you can convert pointer to integer and vice versa is one of the biggest blocks when talking about garbage collector in C++ in general. you can (althoug it's stupid) to serialize the memory address in some external buffer, then re-assign it to some pointer. the GC may think it can delete the variable because nowone else points at it - while the pointer is still "valid" and will be dereference somewhere in the future