So let's say if [I]'m passing array
to function print
. Am I passing address of the first 1-D array (array[0]
) or am [I] just passing the address of the very first variable (array[0][0]
).
You are passing a pointer to the first element of array
, array[0]
, which is itself an array. That pointer has the same value as a pointer to array[0][0]
, but different type. In fact, your code is incorrect in that the argument's type and the function parameter's type do not agree, but as long as the types int(*)[]
and int *
have the same representation, the reinterpretation will work in practice.
And as for the print
function, in this case, am I correct to say that by printing ar[0]
, I am printing array[0][0]
?
Yes, when you call print()
as you do in your example, provided that type representations agree as described above.
But why is it that for the case of printing *(ar+1)
, I am actually printing array[0][1]
instead of array[1][0]
?
Because ar
is a pointer to the first element of array
, i.e. the 1D array array[0]
. Its elements are array[0][0]
, array[0][1]
, etc.. ar + 1
is therefore a pointer to the second element of array[0]
, which is array[0][1]
.
You have two options to make your code correct, both of which might help clarify the issues involved. You could change the argument you pass to print()
to agree with the function:
print(array[0]);
Alternatively, you could change the declared type of print()
's argument, whith a corresponding alteration to its use:
void print(int (*ar)[2]) {
printf("%d\n", ar[0][0]);
printf("%d\n", *(ar+1)[0]);
}
or
void print(int ar[][2]) {
printf("%d\n", ar[0][0]);
printf("%d\n", *(ar+1)[0]);
}
The latter two change the meaning of *(ar + 1)
.