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 Respuestas
+ 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