1

What is really happening here when we provide a definition like below?

int * a = 2;

What is really happening behind the scenes?


SOLVED

Here a will point to memory address 2.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
AAA
  • 348
  • 1
  • 4
  • 19
  • 1
    @AAA--http://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean – inbinder Oct 29 '15 at 02:48
  • 3
    It's making `a` point to memory at address 0x2, which is usually inaccessible and wrong, but won't break until you make the mistake of dereferencing `a`. It's also technically possible for it to do something different that makes sense for the implementation, but in practice, it's just nonsensical. Never do it. – ShadowRanger Oct 29 '15 at 02:54
  • @inbinder If I understood it correctly does it mean that a is holding memory address 2 (or a 3rd byte address). – AAA Oct 29 '15 at 02:55
  • 4
    do not edit a question to mark it **solved**. Just mark the answer that helps you as [accepted](http://stackoverflow.com/help/accepted-answer) is enough – phuclv Oct 29 '15 at 06:01
  • 1
    "Here a will point to memory address 2" is not defined behavior, it is one possible implementation specific result. – chux - Reinstate Monica Oct 29 '15 at 08:32

2 Answers2

4

The result of conversion from integer to a pointer is implementation-defined in C, quoting C99 Section 6.3.2.3:

5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

So you shouldn't rely on such conversion except when the literal is 0 which will give you a null pointer.

In practice you are likely to find that the pointer will hold the memory address specified by the integer constant:

#include <stdio.h>

int main(void) {
  int * a = 2;
  printf("%p", a); /* prints 0x2 in gcc */
  return 0;
}

Most compilers will also warn about this unsafe cast :

 $ gcc test.c test.c: In function ‘main’: test.c:4:13: warning:
 initialization makes pointer from integer without a cast [enabled by
 default]    int * a = 2;
                       ^
vitaut
  • 49,672
  • 25
  • 199
  • 336
0

In here the memory for "a" will not be allocated. So, it gives the segmentation fault error.

It will try to take the 2 as a address and pointer a will try to point the address 2. But it may be our system does not have that address or it may be allocated for some other process.

So, in the compiling time it will give the one warning message.

Warning: initialization makes pointer from integer without a cast [enabled by default]

  • It doesn't give the segmentation fault. – vitaut Oct 29 '15 at 04:44
  • If you will try to use that pointer value a. it will give the segmentation fault. Example printing a value in a pointing address. –  Oct 29 '15 at 04:47