# Discussion Forums

## how can r in the below programme print 1??

New Member
Joined: 5 months  ago
Posts: 1
01/04/2017 12:26 pm

#include<stdio.h>

int main()

{

int x=4;

int *p=&x;

int *k=p++;

int r=p-k;

printf("%d %d %d",r,p,k);

return 0;

}

how can r in the above programme print 1??

New Member
Joined: 4 months  ago
Posts: 1
08/04/2017 6:37 am

yes it is quiet interesting, when we substrct two adresses it is giving 1 as answer , no matter how we arrange it p-k or k-p..

New Member
Joined: 4 months  ago
Posts: 1
13/04/2017 2:18 pm

let me explain this program line by line...

1)   int x = 4;   ->  Declaring an integer X and giving it a value 4.  now the X has an address(not known to us) and a value (which is 4)

2)   int *p = &x;  -> Creating a pointer variable P , and make it pointing at the address of X .  now *p equals to 4. where P equals to whatever the address of X.

3) int *k = p++ ;  -> creating a pointer variable K,  make it equals to P++. here P++ is , pointer moves to next int position.   so the value of K is four address higher than P. and value of *K is four higher than P. (ref image. the image says that the computer always creates four addresses for an declared int by default )

this is the reason for that 4 value fluctuation. not the value of X as four. be clear about that.

4) int r = p - k;  -> integer R is declared. assigned the value as difference of addresses of P & K. which is actually 4 . but the computer consider it as 1. the reason for this is Since both are of same data types, the difference will always be 1 because it is literally the next address for the computer.

so by collecting the above operations, the print f should give the values as,

r -> 1

k -> next address to p (4 added/subtracted to the address of p. for eg. addrs of p = 100. then k here should print 104/96)

ps: (i have been learning my first programming language just now only. am also a noob . so correct me if i am wrong.  i just found ur questn really interesting. so i did some research around and wrote this)

Edited: 4 months  ago

Working

1. Online Compilers - Compile & Run your C/C++ programs: