I think the value of z should be 40 because a[5] has 20 elements, and the space between it and a[3] also has 20 elements. However, the actual value of z is 2.
Can anyone explain this concept?
#include <stdio.h>
int main()
{
int a[10][20];
int z = &a[5] - &a[3];
printf("%d\n", &a[3]); // the address information is 6421740
printf("%d\n", &a[5]); // the address information is 6421900
printf("%d\n", z); // z value is 2. why?
}
Pointer arithmetic is done in the units of the pointed-to type.
In this case a[5] and a[3] are both elements of an array of type int [20], and &a[5] and &a[3] both have type int(*)[20]. They are 2 array element apart, so the difference between them is 2.
It doesn't matter that the underlying type is also an array.
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