双重指针作为函数参数的妙用 | 您所在的位置:网站首页 › c双重指针 › 双重指针作为函数参数的妙用 |
双重指针作为函数参数,可以在函数函数内部修改外部指针的值。主要用法包括: 1. 在函数内部分配内存,作为函数参数返回; 2. 在函数内部设置指针为空; #include #include #include void alloc_mem(int **pp, unsigned int size) { *pp = (int *)malloc(size); printf("alloc_mem: 0x%x\n", *pp); } void my_free(void **p) { if (NULL != *p) { free(*p); *p = NULL; /* set pointer as null, avoid wild pointer */ } } int main() { int *p = NULL; alloc_mem(&p, 8); printf("mem: 0x%x\n",p); my_free((void **)&p); printf("after free, mem: 0x%x\n",p); return 0; }运行结果: alloc_mem: 0x654260 mem: 0x654260 after free, mem: 0x0 3.在函数内部修改外部指针的值;下面的code 在函数内部做了指针++,可以看到setDataCond_1传入了所分配指针的地址,函数内部的(*pp)++修改了外部指针的地址。相反setDataCond却没有修改外部指针的值。 #include #include #include void setDataCond(int *p, unsigned int condi) { if (condi % 2) { *p = condi * 10; } p++; } void setDataCond_1(int **pp, unsigned int condi) { if (condi % 2) { **pp = condi * 10; } (*pp)++; } void setDataCond_2(int **pp, unsigned int condi) { int **cur = pp; if (condi % 2) { **cur = condi * 10; } (*cur)++; } void my_free(void **p) { if (NULL != *p) { free(*p); *p = NULL; } } int main() { unsigned int size = 5; int *p = (int *)malloc(size * sizeof(int)); memset((void *)p, 0, size * sizeof(int)); int *t = p; for (int i=0; i //setDataCond(t+i, i); setDataCond_1(&t, i); //setDataCond_1成功修改t的值 printf("0x%x ", t); }---------------------------------------------------------------------------- setDataCond_2 同setDataCond_1, 不在此赘述。 |
CopyRight 2018-2019 实验室设备网 版权所有 |