Discussion Forums

New User? Please read instructions!

how can r in the below programme print 1??  

  RSS

mahant
New Member
Joined: 3 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??


ReplyQuote
malojinaik8051
New Member
Joined: 3 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.. 


ReplyQuote
haran_kathick
New Member
Joined: 3 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

p -> address of r.

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: 3 months  ago

ReplyQuote
  
Working

Please Login or Register

Ask your questions or clarify your/others doubts from,

✅ Online Discussion Forums by Fresh2Refresh.com





Share this website !!!
Facebook Twitter Linkedin

Close
We Support JALLIKATTU !!!
We Support JALLIKATTU!
By Fresh2Refresh.com
Show Your Support as well. Thanks!