char p1[12] = {1,2,3,4,5,6};
char (*p2)[3];
p2 = &p1;
this is possible, but gcc compiles with a warning:
warning: assignment from incompatible pointer type [- Wincompatible-pointer-types]
char p1[12] = {1,2,3,4,5,6};
char (*p2)[3];
p2 = &p1;
this is possible, but gcc compiles with a warning:
warning: assignment from incompatible pointer type [- Wincompatible-pointer-types]
the following is just a personal understanding. If there are any fallacies, thank you for pointing out.
the first thing to make clear is that
although all pointers are fixed in size (for example, 4 bytes in a 32-bit environment), the pointer itself is typed, that is, each pointer can only point to an object of a specific type (except void * ), such as int * pointer can only point to int type data.
then the array type:
Let's declare an array int a [10]; is convenient to explain.
although in many cases the array name is implicitly converted into a pointer to the first element of the array, giving the illusion of a = & a [0] , the array is indeed a separate type, and you can realize it in two cases-- & a and sizeof (a) ,
& a points to the whole number. When we try to write this, int * p = & a; , compilation cannot pass, and must be written as int (* p) [10] = & a; , that is, a simple int pointer cannot receive the result of & a.
when we print out the result of sizeof (a) , we can see that it is 40 bytes instead of 4 bytes, so obviously the array name and pointer are two different things.
understands that an array is a special type, so we can know that the a just declared above is actually an int array type of length 10, that is, int (*) [10] type. Note that the 10 here cannot be ignored, and the length is part of the array type.
back to the question,
p2 is a pointer because it points to a char array of length 3, so its type is char (*) [3] ,
and p1 is a char array of length 12, so the type of & p1 is: char (*) [12] ,
now assigns & p1 to p2, although both belong to p2. So the compiler will report an error,
if you really want to do this, you need to do a cast:
p2 = (char (*) [3]) & p1;
Previous: Which one has better performance when both Reflect.ownKeys and Object.keys can be used?
Next: On the use of flexible.js in Mobile adaptation Scheme of Mobile Amoy