Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

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 1st one doesn't seem logical to me.

like image 844
Martacus Avatar asked Mar 07 '16 12:03

Martacus


2 Answers

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

enter image description here

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.

like image 50
Sourav Ghosh Avatar answered Oct 21 '22 14:10

Sourav Ghosh


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].

like image 25
Some programmer dude Avatar answered Oct 21 '22 13:10

Some programmer dude