TL;DR
This code contains incorrect and meaningless hacks. There is not much of value to learn from this code.
Detailed explanation follows.
First of all, this is a plain 1D array that gets printed in different ways.
These lines are strictly speaking bugs:
print2((int (*)[2]) a);
print3((int (*)[3]) a);
In both cases there is an invalid pointer conversion, because a
is of type int[6]
and a pointer to the array a
would have to be int (*)[6]
. But the print statements are wrong in another way too, a
when used in an expression like this "decays" into a pointer to the first element. So the code is casting from int*
to int(*)[2]
etc, which is invalid.
These bugs can in theory cause things like misaligned access, trap representations or code getting optimized away. In practice it will very likely "work" on all mainstream computers, even though the code is relying on undefined behavior.
If we ignore that part and assume void print2(int (*a)[2])
gets a valid parameter, then a
is a pointer to an array of type int[2]
.
a[i]
is pointer arithmetic on such a type, meaning that each i
would correspond to an int[2]
and if we had written a++
, the pointer would jump forward sizeof(int[2])
in memory (likely 8 bytes).
Therefore the function abuses this pointer arithmetic on a[i]
to get array number i
, then do [j]
on that array to get the item in that array.
If you actually had a 2D array to begin with, then it could make sense to declare the functions as:
void print (size_t x, size_t y, int (*a)[x][y])
Though this would be annoying since we would have to access the array as (*a)[i][j]
. Instead we can use a similar trick as in your code:
void print (size_t x, size_t y, int (*a)[x][y])
{
int(*arr)[y] = a[0];
...
arr[i][j] = whatever; // now this syntax is possible
This trick too uses pointer arithmetic on the array pointer arr
, then de-references the array pointed at.
Related reading that explains these concepts with examples: Correctly allocating multi-dimensional arrays