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?
A program that uses pointers to access a single element of an array is given as follows − In the above program, the pointer ptr stores the address of the element at the third index in the array i.e 9. This is shown in the following code snippet. The pointer is dereferenced and the value 9 is displayed by using the indirection (*) operator.
So, the size of a pointer to a pointer should have the usual values, that is, 2 bytes for a 16-bit machine, 4 bytes for a 32-bit machine, and 8 bytes for a 64-bit machine. Let us confirm our theoretical knowledge with a program. An array is a contiguous memory block storing data of the same type.
Instead, it depends upon factors like the CPU architecture and the processor’s word size, to be more specific. Thus, the word size is the main determining factor in finding the size of the pointer.
As we already know, the size of the pointer in C is dependent only on the word size of a particular system. So, the size of a pointer to a pointer should have the usual values, that is, 2 bytes for a 16-bit machine, 4 bytes for a 32-bit machine, and 8 bytes for a 64-bit machine.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With