C 3d array pointer decay with & and without &

Note that a is not a pointer is an array.

So when you subtract a pointer to an another pointer. The result is not really an address, It’s numbers of element between them. The type of the result is ptrdiff_t and you should print it with %td.

So when you do &a[1] - &a[0], you ask how many int [][] there are between &a[1] and &a[0] and the answer is 1.

But when you subtract a[1][0] with a[0][0] or a[1] with a[0], you have a undefined behavior because:

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.

a[1][0] and a[0][0] or a[1] and a[0] are not the same array/pointer. So you should not subtract them. But like I say a is an array so you have some result like 6 or 3. There are some special think about an array. But this is just a “luck”, it’s undefined behavior.

You can only do that

&a[i] - &a[j];
&a[i][j] - &a[i][k];
&a[i][j][k] - &a[i][j][l];

In your case, because a is an array:

assert(&a[2] - &a[0] == sizeof a / sizeof *a);

Learn more here and here.

Feel free to tell me I’m wrong. I’m not sure of myself in this answer.

Leave a Comment