int main(void){
int arr[] = {1, 2, 3, 4, 5, 6};
printf("%p\t%p\t%d\n",arr,arr+1,(arr+1)-arr);
return 0;
}
output :
0x7ffe583f4ba0 0x7ffe583f4ba4 1
why is the difference 1? Shouldn't it be 4.
int main(void){
int arr[] = {1, 2, 3, 4, 5, 6};
printf("%p\t%p\t%d\n",arr,arr+1,(arr+1)-arr);
return 0;
}
output :
0x7ffe583f4ba0 0x7ffe583f4ba4 1
why is the difference 1? Shouldn't it be 4.
Think this expression (arr+1)-arr
as
0x7ffe583f4ba0 + 1 - 0x7ffe583f4ba0
it will give 1
.
When you subtract two pointers pointing to the same array then it gives the number of elements between those pointers.
By the same logic, if you increment a pointer to an array of int
by 1 then it will point to it's next element (one unit) and not to the next sizeof(int)
element.
When you perform pointer arithmetic with +
and -
the size of the type pointed to is taken into account:
int main() {
int arr[2] = { 1, 2 };
int *p = arr;
printf("%p -> %d\n", (void *)p, *p);
p++;
printf("%p -> %d\n", (void *)p, *p);
return 0;
}
Output:
0115FCCC -> 1
0115FCD0 -> 2