看下如下各种的区别:
//int *p
//int *p[n] 指针数组
//int (*p)[n] 数组指针
//int *p() 函数返回值
//int (*p)() 函数指针
//int **p 指针的指针
// 常量指针 const char *p; char const *p; 指针的指向可以修改,指向的值不可以修改
// 指针常量 char *p const c; 指向的地址不可以修改
数组指针例子:
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);
}
-> 二维数组
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]);
指针数组:
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里面测试调用 双指针
char zero[] = "jiangde shenme laji chengdu";
char *ret = NULL;
if(find(zero,'l',&ret)){
printf("%s\n",ret);
}
数组名字相当于指针:
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));
}
-> 测试调用
int arr[5] = {1,2,3,4,5};
test6(arr);
printf("%d\n",arr[0]);
函数指针:
void test7(int n){
printf("函数指针:%d\n",n);
}
-> 调用
void (*p)(int);
p = &test7;
p(100);
回调小例子:
int call(int i,int j){
return i+j;
}
int test8(int a,int b,int (* callback)(int,int)){
return (callback(a,b));
}
-> 调用
printf("function callback:%d\n",test8(1,2,call));
网友评论