Why is the answer to this program is 1 ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is the answer to this program is 1 ?

int main() { int x = 4; int *p = &x; int *k = p++; int r = p - k; printf("%d",r); return 0; } Above output is : 1 Why so?

29th Sep 2021, 10:51 PM
Bart
Bart - avatar
2 Answers
+ 6
Here is explanation of how that code works: int x = 4 //creates variable x with value 4 int *p = &x; //creates pointer p to value '4' int *k=p++; //creates duplicate of pointer k //And increases p by one (as pointer //is an address in the memory) int r = p- k; // As p has an address of (&x)+1 and //has address of just &x p-k=1 // // so basically both p and k hold // a number which is an address in // memory to variable x, the only difference is // that you incremented p, therefore p is bigger // than k by 1 // // so this line creates variable with //value of 1 printf("%d", r); // system function for printing to //console. That prints out value of r //as integer (which is 1)
29th Sep 2021, 11:17 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
0
This is not csharp use proper tag Here you have declared one integer variable int x=4 Then in next line you have declared one more pointer variable p which contains the address of x and . Then in line no 3 you have declared one more pointer variable *k which and u assigned p address here but *k will print the value of p and it will assign to *k but ++ Post increment will increase by one after assigning the value so the current value of p become 5 after increment and k become 4 Then in line no 4 you calculating subtraction of both value p- k It will give result as 1
30th Sep 2021, 1:48 PM
A S Raghuvanshi
A S Raghuvanshi - avatar