Consider the following in C
int arr[]= {1,2,3,4,5};
My system uses 4 bytes to store int data.
Now &arr[0] => 0022FEB0
and &arr[1]=>0022FEB4
at a moment of run
Now
int diff=&arr[1]-&arr[0];
Value stored in diff is 1
and not 4
.
Why?
Consider the following in C
int arr[]= {1,2,3,4,5};
My system uses 4 bytes to store int data.
Now &arr[0] => 0022FEB0
and &arr[1]=>0022FEB4
at a moment of run
Now
int diff=&arr[1]-&arr[0];
Value stored in diff is 1
and not 4
.
Why?
That's the way pointers work. You are not calculating the byte difference. You're calculating the difference in number of elements.
To get the element size, use sizeof(*arr)
To get the byte difference, use (&arr[1]-&arr[0]) * sizeof(*arr)
I think that what you want it this:
int diff = (&arr[1]-&arr[0]) * sizeof(int);
When you tells to compiler the data type you are working with, it will consider it in the arithmetic.
You are not calculating the byte difference. To calculate byte difference there is already an answer on StackOverflow. here is a link to answer Getting the difference between two memory addresses
The compiler knows that types of substracted ones whose are pointer to int
.
#include <stdio.h>
#include <stddef.h>
int main(void) {
int arr[]= {1,2,3,4,5};
/*
int diff=&arr[1]-&arr[0];
In your system, there's a 4 byte difference in memory, so you'd get diff = 1
here because the compiler knows they're ints so the result is diff/sizeof(int)
*/
uintptr_t firstNumAddress = (uintptr_t)&arr[0];
uintptr_t secondNumAddress = (uintptr_t)&arr[1];
ptrdiff_t ptrDiff = secondNumAddress - firstNumAddress;
printf("%lu - %lu = %ti\n", secondNumAddress, firstNumAddress, ptrDiff);
return 0;
}
You are doing pointer arithmetic, instead of integer arithmetic.
To do integer arithmetics, just cast the addresses to an integer type of the same size in bytes of a pointer (in 32-bit systems, that can be 4 bytes; in 64-bit, that can be 8 bytes).
For example, in C, just do:
int diff = (uintptr_t) &arr[1] - (uintptr_t) &arr[0];
And you get the difference in bytes.