看下如下各種的區(qū)別:
//int *p
//int *p[n] 指針數(shù)組
//int (*p)[n] 數(shù)組指針
//int *p() 函數(shù)返回值
//int (*p)() 函數(shù)指針
//int **p 指針的指針
// 常量指針 const char *p; char const *p; 指針的指向可以修改皮服,指向的值不可以修改
// 指針常量 char *p const c; 指向的地址不可以修改
數(shù)組指針例子:
int array[] = {1, 2, 3, 4, 5};
int (*ptr_array)[5] = &array;
int *p = NULL;
int i = 0;
for (i = 0; i < 5; i++) {
printf("array[%d]=%d, *(array+%d)=%p\n", i, array[i], i, *(ptr_array + 1));
printf("&array[%d]=%p, array+%d=%p\n", i, &array[i], i, array + i);
}
for (p = array; p < array + 5; p++) {
printf("p=%p,*p=%d\n", p, *p);
}
-> 二維數(shù)組
int arr[][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
int (*ptr_arr)[3] = arr;
printf("%d\n", *(*(ptr_arr + 1) + 1));
printf("%d\n", arr[1][1]);
指針數(shù)組:
int *color[] = {"red", "green", "blue"};
int i;
for (i = 0; i < 3; i++) {
puts(color[i]);
printf("color[%d]=%p\n", i, &color[i]);
color[i] = "colors";
printf("color[%d]=%p\n", i, &color[i]);
}
查找字符串的例子:
int find(const char *src, char ch, char **ret) {
char * index = (char *)src;
while (*index){
if(*index == ch){
*ret = index;
return 1;
}
index ++;
}
return 0;
}
-> 在main里面測(cè)試調(diào)用 雙指針
char zero[] = "jiangde shenme laji chengdu";
char *ret = NULL;
if(find(zero,'l',&ret)){
printf("%s\n",ret);
}
數(shù)組名字相當(dāng)于指針:
void test5(int array[]){
printf("%d size\n", sizeof(array));
array[0] = 100;
printf("%d size\n", sizeof(array));
}
void test6(int *array){
printf("%d size\n", sizeof(array));
array[0] = 100;
printf("%d size\n", sizeof(array));
}
-> 測(cè)試調(diào)用
int arr[5] = {1,2,3,4,5};
test6(arr);
printf("%d\n",arr[0]);
函數(shù)指針:
void test7(int n){
printf("函數(shù)指針:%d\n",n);
}
-> 調(diào)用
void (*p)(int);
p = &test7;
p(100);
回調(diào)小例子:
int call(int i,int j){
return i+j;
}
int test8(int a,int b,int (* callback)(int,int)){
return (callback(a,b));
}
-> 調(diào)用
printf("function callback:%d\n",test8(1,2,call));