First: pointers must be cast to (void*)
and printed with %p
. %d
prints an int
in base 10. That is,
#include <stdio.h>
int main(){
int i;
int *p = (int*) i;
printf("\n p is %p ", (void*)p);
int *q = &i;
printf("\n q is %p ", (void*)q);
}
Now let's try to compile the program with these changes: only 2 errors:
% gcc ptr.c -Wall -Wextra
ptr.c: In function ‘main’:
ptr.c:5:14: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
int *p = (int*) i;
^
ptr.c:5:14: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
int *p = (int*) i;
^~~~~~~~
Both pertanining to the int *p = (int*) i;
; the second says that the value of i
is used but we didn't set any value to i
(this causes undefined behaviour) and the other that we're trying to convert an integer to a pointer, and the integer doesn't have the same amount of bits as a pointer has on this platform.
I.e.
int *q = &i;
initializes pointer to int q
with the address of variable i
, whereas
int *p = (int*) i;
interprets the garbage value contained in i
, in an implementation-defined manner, as an address, and initializes p
with that.
Not quite equal.