+ 3

Hello EveryoneđŸ™‹đŸ»â€â™‚ïž, I have doubt in following C code. Could anyone help me? đŸ™đŸ» Please... [Code is in discription]

#include <stdio.h> int main() { int x =4; int* ptr=&x; int* k= ptr++; int r= ptr-k; printf("r is %d",r); return 0; } Output: r is 1 And I am thinking that output should be 4.

28th Jan 2021, 4:00 AM
Rohit Rathod
Rohit Rathod - avatar
4 Answers
+ 6
Rohit Rathod you're right that the difference in bytes is the size of an int. Subtracting 2 pointers gives you the difference not in bytes but in chunks of that type's size. So to get difference in bytes you would do: (ptr - k) * sizeof(int) Since a char is 1 byte, if we cast ptr and k to pointers to chars you would get the difference in bytes: printf("%d", (char*)ptr - (char*)k); // 4 https://stackoverflow.com/questions/9855482/pointer-address-difference
28th Jan 2021, 7:28 AM
jtrh
jtrh - avatar
+ 4
int r= ptr-k; r is the difference between pointers ptr and k. int* ptr=&x; Initially ptr points to x. For example, let's say x resides at the memory address 1000 (int chunks, not bytes). int *k= ptr++; Post-increment is functionally equivalent to: int* k = ptr; // k = 1000 ptr = ptr + 1; // ptr = 1000 + 1 = 1001 Therefore r is 1: int r= ptr-k; // r = 1001 - 1000 = 1 The value of x does not matter because you never dereference any pointers.
28th Jan 2021, 4:46 AM
jtrh
jtrh - avatar
+ 2
jtrh thank you so much brother for your answer. But my point of view is that when a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int) and the new address it will points to 1004. That's why I am thinking that answer should be 4.
28th Jan 2021, 7:08 AM
Rohit Rathod
Rohit Rathod - avatar
+ 2
jtrh thank you so much. Now I understood.
28th Jan 2021, 7:57 AM
Rohit Rathod
Rohit Rathod - avatar