0

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

Akash Gutha
  • 601
  • 8
  • 21
  • `p` is not an `int` --> `printf("%d\n" , p);` is not good code. Better to use `printf("%p\n" , p);`. Best to use `printf("%d\n" , (void *) p);` – chux - Reinstate Monica Jan 09 '15 at 02:36
  • There's no difference on most sane hardware. In fact casting a pointer to `void *` before stuffing it in a `varargs` does nothing. You could argue that `"%p"` prints it in a more readable fashion, sure, but textbook warnings mean very little in the real world. – Blindy Jan 09 '15 at 02:42

5 Answers5

2

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.

VHarisop
  • 2,816
  • 1
  • 14
  • 28
1

This statement

int *p = &i;

Means this:

int *p;
p = &i;

p is defined as an integer pointer (int *), then it is assigned the value &i (address of the integer variable i).

This is not the same as *p = &i

Aziz
  • 20,065
  • 8
  • 63
  • 69
1

To be less confused, you can use:

int* p = &i;

Then, you can always keep in mind that p is referring to address and *p referring to value

anhlc
  • 13,839
  • 4
  • 33
  • 40
0

I highly accept the second definition, because it is the proper way to define a pointer. You see, you are supposed to define the header, and then assign it the variable to point to, without the *.

DripDrop
  • 994
  • 1
  • 9
  • 18
0

If i is a variable holding 10, and you define p as an int * holding the address of i, then your statements mean:

printf("Hello world!\n %d , %d \n" , 
    *p ,    // value inside p, ie value of i, 10
    p);     // value OF p, which is the address of i
Blindy
  • 65,249
  • 10
  • 91
  • 131