I've been trying to work with pointers and i've encountered this problem. In this code .. p,h are two pointers ... i've equated *p = &i , h = &j ; and printed the values my expectation was that *p will contain the address and p will have the address pointing to i , and in h's case h will have the address and *h will o/p the value of j.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i =10;
int *p = &i;
int j =30;
int *h;
h = &j;
printf("Hello world!\n %d , %d \n" , *p , p);
printf("Hello world!\n %d , %d \n" , *h , h);
return 20;
}
But my o/p in case of p and i is reversed .. Why is it so .. How does the compiler differentiate b/w these two kind of statements .... *p = &i ; and *p = i;
the o/p is like this
Hello World!
10 , 2359060
Hello World!
30, 2359056
I'm sorry if the Question title was is wrong .. I didn't know how to describe the situation .. any links to similar problems will be appreciated
The statement
int *p = &i;
declares p
as a pointer to int, and initialises it with the address of i. It's like writing
int *p;
p = &i;
After these statements, p
contains the address of i
, and *p
the value of i
.
As John Kugelman pointed out, use the %p
format specifier to print pointers.