Intuitive understanding:
1. char(*p)[10] is a pointer to an array.
2. char p[10] is an array p.
3. char *p[10] is an array of pointers, and the array elements are char* pointers.
Specific differences:
1. A pointer to an array
In char(*p)[10], p points to an array of 10 char size, the difference between p+1 and p is sizeof(char p[10]), p+1 has pointed to another same size array too.
2. Array pointer
In char p[10], p is also a pointer, but a constant pointer, pointing to the address of the first element of the array (not the first address of the array) , see the following code:
- #include <stdio.h>
- intmain ()
- {
- char (*p)[10] ;
- char a[10];
- p=a;
- }
test.c: in function 'main':
test.c:6: warning: assignment from incompatible pointer type?
You just change p=a to p=&a That's it.
This is where the c language confuses people. Many books tell you that the array name is the address of the array, but in fact it is the address of the first element of the array, and the type is char *. And &a represents the address of the array, and the type is char (*)[10] . Since the address of the array above the value is the same as the value of the address of the first element of the array, everyone usually thinks that &a and a are the same, resulting in a misunderstanding.
So, the warning for p=a is that you assign the address of a char to a pointer to char (*)[10]. Of course, the result is correct, but with a caveat.
3. Array of pointers
char * p[10], represents an array, each element in the array is a pointer, where sizeof(p) should be 40 on a 32-bit machine, =10 * sizeof(char*), here is the length of the array , rather than the length of the pointer, it also means that it is an array, which is also different from the pointer to the pointer (char **p)
also:
- char *p;
- char a[10];
- p = a;
Here p = a means that p points to the address of a[0], and p points to a char.
If it is changed to p = &a, it means that p points to the array a, and p points to an a[10] array at this time!
p 仅仅是指向一个元素,而&a是整个数组的地址(&a实际上是指向数组a的指针),一个元素是不能指向整个数组的,因为它们类型不一致,编译器会警告!!!
虽然编译时会提醒警告:不兼容的指针类型,但还是能运行,实际上这是不对的。
正确的代码应该是: