Akash Gutha
Akash Gutha

Reputation: 599

How does these Pointer statements differ *p = &i , h = &j?

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

Upvotes: 0

Views: 4844

Answers (5)

anhlc
anhlc

Reputation: 14469

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

Upvotes: 1

Blindy
Blindy

Reputation: 67447

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

Upvotes: 0

VHarisop
VHarisop

Reputation: 2826

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.

Upvotes: 2

Aziz
Aziz

Reputation: 20745

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

Upvotes: 1

DripDrop
DripDrop

Reputation: 1002

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 *.

Upvotes: 0

Related Questions