I'm trying to find the distance in memory between two variables. Specifically I need to find the distance between a char[] array and an int.
char data[5];
int a = 0;
printf("%p\n%p\n", &data[5], &a);
long int distance = &a - &data[5];
printf("%ld\n", distance);
When I run my my program without the last two lines I get the proper memory address of the two variables, something like this:
0x7fff5661aac7
0x7fff5661aacc
Now I understand, if I'm not wrong, that there are 5 bytes of distance between the two (0x7fff5661aac8, 0x7fff5661aac9, 0x7fff5661aaca, 0x7fff5661aacb, 0x7fff5661aacc).
Why I can't subtract a pointer of type (int *) and one of type (char *). Both refer to memory address.. What should I do in order to calculate the distance, in bytes, between the two?? I tried casting one of the two pointers but it's not working.
I get: "error: 'char *' and 'int *' are not pointers to compatible types". Thanks to everyone will help me
Nopes, this is not possible.
First, you can only subtract pointers of (to) "compatible" types, an int
and a char
are not compatible types here. Hence the subtraction is not possible.
That said, even if both are pointers to compatible type, then also, the following comes into picture.
So, secondly You cannot just subtract two arbitrary pointers, they need to be essentially part of (address for elements of) the same array. Othweise, it invokes undefined behavior.
Quoting C11
, chapter §6.5.6, Additive operators
When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. [....]
Thirdly, another important point, the result of subtraction of two pointers is of type ptrdiff_t
, a signed integer type.
[...] The size of the result is implementation-defined, and its type (a signed integer type) is
ptrdiff_t
defined in the<stddef.h>
header. [...]
so, to print the result, you need to use %td
format specifier.