C Code explanation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C Code explanation

This question was in C challenge What will be the output of the following code: int x = 4; int *p = &x; int *k = p++; int r = p - k; printf(ā€œ%i\nā€, r); The output was 1 can anyone explain why??!

4th Apr 2020, 6:01 PM
Mostafa Ehab
Mostafa Ehab - avatar
3 Answers
+ 2
As BahhašŸ§ has stated, the code raises an error. I think instead of int* k = p**; the original line was int* k = p++; because then one would be the correct output, since pointer subtraction yields the distance between pointers, i.e. the amount of memory blocks the pointers are apart from each other, where the block size is defined by the size of the data type they are pointing two. By post-incrementing 'p', the pointer 'k' would point to 'x', while 'p' now points to the next memory cell, so the distance between them is one.
4th Apr 2020, 6:20 PM
Shadow
Shadow - avatar
+ 1
it should output an error because int *k = p**; doesn't make any sense.
4th Apr 2020, 6:08 PM
Bahhaāµ£
Bahhaāµ£ - avatar
+ 1
Shadow BahhašŸ§ yes my mistake Iā€™ve changed it , I got the answer shadow thank you šŸ‘
4th Apr 2020, 6:48 PM
Mostafa Ehab
Mostafa Ehab - avatar