双重指针作为函数参数的妙用
雙重指針作為函數參數,可以在函數函數內部修改外部指針的值。主要用法包括:
1. 在函數內部分配內存,作為函數參數返回;
2. 在函數內部設置指針為空;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>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 <stdio.h>
#include <stdlib.h>
#include <string.h>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<size; i++){setDataCond(t+i, i);//setDataCond_1(&t, i);printf("0x%x ", t);}printf("\n");for (int i=0; i<size; i++){printf("%d ", *(p+i));}printf("\n");my_free(&p); //free(p);//p = NULL;return 0;
}
調用 setDataCond(t+i, i);運行結果:
0x2521010 ?0x2521010 ?0x2521010 ?0x2521010 ?0x2521010 ?
0 10 0 30 0?
?? ?for (int i=0; i ?? ?{
?? ??? ?setDataCond(t+i, i);? //setDataCond并沒有修改t的值,依靠t+1完成循環打印。
?? ??? ?//setDataCond_1(&t, i);
?? ??? ?printf("0x%x ?", t);
?? ?}
----------------------------------------------------------------------------
?調用?setDataCond_1(&t, i);運行結果:
0x18f6014 ?0x18f6018 ?0x18f601c ?0x18f6020 ?0x18f6024 ?
0 10 0 30 0?
?? ?for (int i=0; i ?? ?{
? ? ? ? //setDataCond(t+i, i);?
?? ??? ?setDataCond_1(&t, i); //setDataCond_1成功修改t的值
?? ??? ?printf("0x%x ?", t);
?? ?}
----------------------------------------------------------------------------
setDataCond_2 同setDataCond_1, 不在此贅述。
總結
以上是生活随笔為你收集整理的双重指针作为函数参数的妙用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求一个好听的蚂蚁名字。
- 下一篇: 连续地址数据(数组或者malloc的内存