函数指针与指针运算
1. 多级指针
#include <stdio.h>
void update(int * i) {
printf("update函数,i的内存地址是:%p\n", i);
* i = 999;
}
int mainT1() {
int i = 100;
update(&i);
printf("main函数,i的内存地址是:%p\n", &i);
return 0;
}
#include <stdio.h>
int mainT2(){
int num = 999;
int * num_p = #
int ** num_pp = &num_p;
int *** num_ppp = &num_pp;
printf("num_p的值是:%p, num_pp的值是:%p\n", num_p, num_pp);
printf("二级指针获取最终的值:%d\n", **num_pp);
printf("三级指针获取最终的值:%d\n", *** num_ppp);
return 0;
}
2. 数组与数组指针
#include <stdio.h>
int mainT3() {
int arr[] = {1,2,3,4};
int i = 0;
for (i = 0; i < 4; ++i) {
printf("%d\n", arr[i]);
}
printf("arr = %d\n", arr);
printf("&arr = %d\n", &arr);
printf("&arr[0] = %d\n", &arr[0]);
int * arr_p = arr;
printf("%d\n", *arr_p);
arr_p ++;
printf("%d\n", *arr_p);
arr_p += 2;
printf("%d\n", *arr_p);
arr_p -= 3;
printf("%d\n", *arr_p);
arr_p += 2000;
printf("%d\n", *arr_p);
return 0;
}
3. 采用指针遍历数组
#include <stdio.h>
int mainT4() {
int arr[] = {1,2,3,4};
int * arr_p = arr;
int i = 0;
for (i = 0; i < 4; ++i) {
printf("位置%d的值是:%d\n", i, * (arr_p + i));
printf("位置%d的内存地址是:%p\n", i, (arr_p + i));
}
return 0;
}
4. 循环时给数组赋值
#include <stdio.h>
int mainT5() {
int arr[4];
int * arrP = arr;
int j = 0;
for (j = 0; j < 4; ++j) {
* (arrP + j) = (j + 10001);
}
for (int i = 0; i < sizeof arr / sizeof(int); ++i) {
printf("位置%d的值是:%d\n", i, * (arrP + i));
}
return 0;
}
5. 数组指针操作的几种方式
#include <stdio.h>
int mainT6(){
int arr[] = {1,9,0,9999};
int * arrP = arr;
for (int i = 0; i < sizeof arr / sizeof(int); ++i) {
printf("%d\n", arrP[i]);
printf("---%d\n", *(arrP + i));
}
}
6. 指针类型有何用?
#include <stdio.h>
int mainT7() {
int num = 12;
int * num_p = #
double * num_p_d = num_p;
printf("%d\n", sizeof num_p);
printf("%d\n", sizeof num_p_d);
char c = 'a';
return 0;
}
7. 函数指针
#include <stdio.h>
void add(int num1, int num2);
void mins(int num1, int num2) {
printf("num1 - num2 = %d\n", (num1 - num2));
}
void opreate(void(*method)(int,int), int num1, int num2) {
method(num1, num2);
printf("opreate函数的 method指针是多少:%p\n", method);
}
int mainT8() {
opreate(add, 10, 10);
opreate(mins, 100, 10);
printf("main函数的 add指针是多少:%p\n", add);
printf("main函数的 mins指针是多少:%p\n", mins);
printf("%p, %p\n", add, &add);
return 0;
}
void add(int num1, int num2) {
printf("num1 + num2 = %d\n", (num1 + num2));
}
#include <stdio.h>
void callBackMethod(char * fileName, int current, int total) {
printf("%s图片压缩的进度是:%d/%d\n", fileName, current, total);
}
void compress(char * fileName, void(*callBackP)(char *,int,int)) {
callBackP(fileName, 5, 100);
}
int main() {
void (* call) (char *, int ,int);
call = &callBackMethod;
void (* call2) (char *, int ,int);
void (* call3) (char *, int ,int);
void (* call4) (char *, int ,int);
void (* call5) (char *, int ,int);
call5 = &callBackMethod;
compress("derry.png", call5);
}