This is my code:
int m[][3] = {
{ 0 , 1 , 2 },
{ 10, 11, 12 },
{ 20, 21, 22 }
};
printf("%d %d\n", m[1] - m[0], m[1][0] - m[0][0]);
And why does
m[1] - m[0]
return 3
? I know why the second expression would return 10
but the 1st one doesn't seem logical to me.
In your code:
m[1] - m[0]
denotes a pointer subtraction which gives you the difference of the two pointers based on the type. In this case, both the pointers are differentiated by 3 elements, so the result is 3.
To quote C11
standard, chapter §6.5.6
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. [...]
and
[...] In other words, if the expressions
P
andQ
point to, respectively, thei
-th andj
-th elements of an array object, the expression(P)-(Q)
has the valuei−j
provided the value fits in an object of typeptrdiff_t
. [....]
To help visualize better, please see the following image
Here, s
is a two dimensional array, defined as s[4][2]
. Considering the data type of the array consumers 2 byte each, please follow the elements (index) and corresponding memory location (arbitrary). This will give a better understating how actually in memory, the array elements are contiguous.
So, as per the representation, s[0]
and s[1]
are differentiated by two elements, s[0][0]
and s[0][1]
. Hence, s[1] - s[0]
will produce a result of 2.
Because the "difference" between m[1]
and m[0]
is three elements.
It might be easier to understand if you look at it like this
m[0] m[1] m[2] | | | v v v +---------+---------+---------+---------+---------+---------+---------+---------+---------+ | m[0][0] | m[0][1] | m[0][2] | m[1][0] | m[1][1] | m[1][2] | m[2][0] | m[2][1] | m[2][2] | +---------+---------+---------+---------+---------+---------+---------+---------+---------+
The difference between m[1]
and m[0]
is the three elements m[0][0]
, m[0][1]
and m[0][2]
.
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