How can I know the distance in bytes between 2 pointers? For example:
I would like to know how many bytes there are between p2 and p1 ( in this case 3) because to reach p2 with p1 I have to do 3 steps...
step1 p1 is in B
step2 p1 is in C
step3 p1 is in D
so i need that return to me 3
I'm asking this type of question because I'm implementing the lz77 algorithm
Two pointers can also be subtracted from each other if the following conditions are satisfied: Both pointers will point to elements of same array; or one past the last element of same array. The result of the subtraction must be representable in ptrdiff_t data type, which is defined in stddef. h .
The time complexity of this solution is O(n) because each element is visited at most twice. In the worst case scenario, all elements will be visited once by the start pointer and another time by the end pointer. The space complexity would be O(1) because the solution doesn't create new data structures.
One pointer starts from the beginning while the other pointer starts from the end. The idea is to swap the first character with the end, advance to the next character and swapping repeatedly until it reaches the middle position. We calculate the middle position as ⌊ n 2 ⌋ \lfloor\frac{n}{2}\rfloor ⌊2n⌋.
Pointer Subtraction It turns out you can subtract two pointers of the same type. The result is the distance (in array elements) between the two elements. This can result in negative values if p2 has a smaller address than p1. p2 and p1 need not point to valid elements in an array.
You could try with:
ptrdiff_t bytes = ((char *)p2) - ((char *)p1);
But this only works as expected if the pointers you subtract point to the same single piece of memory or within it. For example:
This will not work as expected:
char *p1 = malloc(3); // "ABC", piece 1
char *p2 = malloc(3); // "DEF", piece 2
char *p3 = malloc(3); // "GHI", piece 3
ptrdiff_t bytes = p3 - p1; // ABC ... DEF ... GHI
// ^ ^
// p1 p3
// Or:
// GHI ... ABC ... DEF
// ^ ^
// p1 p3
// Gives on my machine 32
printf("%td\n", bytes);
Because:
However this will work:
char *p1 = malloc(9); // "ABCDEFGHI", one piece of memory
char *p2 = p1 + 3; // this is within the same piece as above
char *p3 = p2 + 3; // this too
ptrdiff_t bytes = p3 - p1; // ABC DEF GHI
// ^ ^
// p1 p3
// Gives the expected 6
printf("%td\n", bytes);
Because:
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