tonybai在他的网站上写了一个本书的知识点纲要
An array name is not a pointer. Although an array name can be treated as a pointer at
times, and array notation can be used with pointers, they are distinct and cannot always
be used in place of each other
一维数组
对于数组使用sizeof会返回数组所占用内存的大小,如:
int vector[5];
printf("%d ",sizeof(vector) / sizeof(int)); /*输出5*/
指针记号法与数组(Pointer Notation and Arrays)
数组名只能做右值,在在做右值时返回数组首元素的首地址
int vector[5] = {1,2,3,4,5};
int *pv = vector; //变量pv是指向数组首元素的指针,而不是指向数组的指针
三种表达方式,vector,&vector[0],&vector数值上是相同的,但是含义有差别:
vector和&vector[0]意思相同,指向数组首元素的首地址,
&vector指向数组的地址
所以如果进行指针运算,那么vector + 1,指向数组的第二个元素,&vector + 1指向下一个同样长度的数组,
如果将vector和&vector看做指针的话,vector是指向数组元素的指针,&vector是指向数组的指针也就是数组指针
在上边的例子中,如果我们修改程序,在gcc中会如下:
int vector[5] = {1,2,3,4,5};
int *pv = &vector; //Gcc警告:warning: initialization from incompatible pointer type,这样做不恰当
既然&vector是数组指针,如果不想看到警告,则需要如下修改程序
int vector[5] = {1,2,3,4,5};
int (*pv)[5] = &vector; //pv声明为数组指针,再编译就不会报错,(*pv)的括号是必不可少的,去掉就变成另外的意思了
Array notation can be thought of as a “shift and dereference” operation. The expression
vector[2] means start with vector, which is a pointer to the beginning of the array, shift
two positions