知识点:
pointer arithmetic
char *p; p+1 地址加1,因为char 是1个byte
int *p; p+1地址加4,因为p是4个byte
array of pointer
int p; integer
int p[2]; array
int *p[2]; array of pointer p[i] = &a[i]; 指针数组里面每个元素都是存的地址
pass pointer to function
int add( int a, int *p)
{
int c;
c = a + *p;
return c;
}
数组名是数组首地址,因此也可以当做指针传递给函数
int func( int *p)
{
int c;
c = p[i]; // 注意是 p[i]而不是 *p[i];虽然p是指针
return c; //正常是 *(p + i),但是括号写起来太麻烦了,所以给你一个捷径写成 p[i]
}
函数返回指针
int * func(void)
{
static int a; // 注意要是static,不然返回的指针会变,没有意义
int *c = &a;
return c;
}
pointer to function
int ( * P_function) (int ); // 注意必须要小括号 braces 把它括起来 ,不需要给函数形参名字
int * P_function (int ); // 没有小括号,就变成了函数的返回值,是一个int型的指针
int (* pfAddTwoNumber) (int, int) = AddTwoNumber; //跟数组一样,函数名就是函数的首地址,因此可以直接赋值给函数指针
Dangling, Void , Null and Wild Pointer in C
Dangling pointer: dangling pointer is a pointer that not pointing a valid object (object is deleted or deallocated) // 例如pointer指向的是一个local variable,函数执行完就被释放了
Wild pointer: A pointer that is not initialized properly prior to its first use is known as the wild pointer
NULL pointer: pointer point to nothing
void pointer: has no associated data type. It can store the address of any type of object and it can be type-casted to any type //void指针赋给别的类型时必须强制类型转换 type-casted
i++, ++i
i = 0;
j = i++; // j =0 ++在后面就是先赋值,再自加
k = ++i; // k =1 ++在前面就是先自加,再赋值
常见面试题:
一个指针可以是volatile 吗?解释为什么 当然可以, volatile int *p; 代表该指针p指向的变量是volatile类型的,编译器读取的时候不要去优化它