Why does m[1] – m[0] return 3 where m is a 3×3 matrix?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)