简体   繁体   中英

Why we can't assign value to pointer

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM