#include<stdio.h>
int main(int argc , char *argv[])
{
int array[2][2] = {{1,100},{1000,10000}};
int *pointer = array;
int *ppointer = &array;
int *pppointer = array[0];
int *ppppointer = &array[0];
printf("%d\n",*pointer);
printf("%d\n",*ppointer);
printf("%d\n",*pppointer);
printf("%d\n",*ppppointer);
return 0;
}
Four pointers are point to the first element of array.
which definition shown above is better?
And I don’t known why the same value to array and &array?
The only reason all for of your definitions compile is that your C compiler is too permitting when it comes to pointer type conversions. If you use some switches that make it more pedantic in this regard, it should immediately tell you that only the third initialization is valid, while the rest are erroneous.
In most contexts (with a few exceptions) when array of type
T[N]is used in an expression, it “decays” (gets implicitly converted) to pointer typeT *– a pointer that points to its first element. In other words, in such contexts for any arrayA, theAexpression is equivalent to&A[0]. The only contexts where array type decay does not occur are unary&operator,sizeofoperator and string literal used as an initializer for achararray.In your example
arrayis a value ofint [2][2]type. When used on the right-hand side of initialization it decays to pointer typeint (*)[2]. For this reason this is invalidThe right-hand side is
int (*)[2], while the left-hand side isint *. These are different pointer types. You can’t initialize one with the other.The
is exactly equivalent to the previous one: the right-hand side produces a value of
int (*)[2]type. It is invalid for the very same reason.The
&arrayexpression produces a pointer ofint (*)[2][2]type. Again, for this reasonis invalid.
The only valid initialization yo have in your example is
array[0]is an expression ofint [2]type, which decays toint *type – the same type that you have on the left-hand side.In other words there’s no question of which one “better” here. Only one of your initialization is valid, others are illegal. The valid initialization can also be written as
for the reasons I described above. Now, which right-hand side is “better” (
array[0]or&array[0][0]) is a matter of your personal preference.In order to make your other initializations valid, the pointers should be declared as follows
but such pointers will have different semantics from an
int *pointer. And you apparently needint *specifically.