简体   繁体   中英

Why does m[1] - m[0] return 3 where m is a 3x3 matrix?

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 1 st 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 and Q point to, respectively, the i -th and j -th elements of an array object, the expression (P)-(Q) has the value i−j provided the value fits in an object of type ptrdiff_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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM