c - How exactly pointer subtraction works in case of integer array? -
#include<stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf("number of elements between 2 pointer are: %d.", (ptr2 - ptr1)); printf("number of bytes between 2 pointers are: %d", (char*)ptr2 - (char*) ptr1); return 0; } for first printf() statement output 5 according pointer subtraction confusion
what second printf() statement, output?
to quote c11, chapter §6.5.6, additive operators
when 2 pointers subtracted, both shall point elements of same array object, or 1 past last element of array object; result difference of subscripts of 2 array elements.
so, when you're doing
printf("number of elements between 2 pointer are: %d.", (ptr2 - ptr1)); both ptr1 , ptr2 pointers int, hence giving difference in subscript, 5. in other words, difference of address counted in reference sizeof(<type>).
otoh,
printf("number of bytes between 2 pointers are: %d", (char*)ptr2 - (char*) ptr1); both ptr1 , ptr2 casted pointer char, has size of 1 byte. calculation takes place accordingly. result: 20.
fwiw, please note, subtraction of 2 pointers produces result type of ptrdiff_t , should using %td format specifier print result.
Comments
Post a Comment