-1

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.

Community
  • 1
  • 1
Hassaan Salik
  • 413
  • 4
  • 22
  • 3
    Because `int *ptr=7ffff3a9ae94;` is invalid syntax. – Jongware Jun 08 '15 at 14:00
  • It doesn't make a sence to hardcode address of pointer to **dynamic** memory. – cybersoft Jun 08 '15 at 14:01
  • You cannot store a hex value like `7ffff3a9ae94` in an `int` . There are some protocols to be followed or you need to create one and make sure others follow too. – Vinay Shukla Jun 08 '15 at 14:02
  • Pointers work like other variables/types in the sense that they hold a value as well. They work differently in the sense that the value they hold is an address in memory. You cannot hardcode a memory address, getting a free block of memory is an operation which has to be requested to the OS. – aslg Jun 08 '15 at 14:07
  • 1
    @yanivx: The main problem would be that `int` might not be big enough, but "hex value" has nothing to do with it. `0x7fff` will always fit. – MSalters Jun 08 '15 at 14:55

1 Answers1

2

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

David Haim
  • 25,446
  • 3
  • 44
  • 78
  • 1
    C++11 addresses that GC problem. See [`std::pointer_safety`](http://en.cppreference.com/w/cpp/memory/gc/pointer_safety) – MSalters Jun 08 '15 at 14:57