多级指针传入传出

对于主函数的二级指针的分配赋值操作,调用函数时会用到三级指针来指向存储二级指针的内存地址

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int getMem(char ***p3,int num)
{
    int i = 0;
    char ***tmp = NULL;
    
    if(p3 == NULL)
    {
        return -1;
    }
    
    tmp = (char **)malloc(sizeof(char *) * num);
    if(tmp == NULL)
    {
        return NULL;
    }
    
    for(i = 0; i < num; i++)
    {
        tmp[i] = (char *)malloc(sizeof(char) * 100);
        sprintf(tmp[i],"%d%d%d",i+1,i+1,i+1);
    }
    
    *p3 = tmp;
    
    return 0;
}

int getMem_free(char ***p3,int num)
{
    int iRet = -1;
    int i = 0;
    char ***tmp = NULL;
    
    if(p3 == NULL)
    {
        return;
    }
    
    tmp = *p3;
    
    for(i = 0; i < num; i++)
    {
        free(tmp[i]);
        iRet = 0;
    }
    
    free(tmp);
    
    *p3 = NULL;
    return iRet;
}

int main()
{
    int iRet = 0;
    int i = 0, j = 0;
    char **p2 = NULL;
    int num = 5;
    char *tmp = NULL;
    
    getMem(&p2,num);
    
    for(i = 0; i < num; i++)
    {
        printf("%s \n",p2[i]);
    }
    
    iRet = getMem_free(&p2,num);
    if( 0 == iRet)
    {
        printf("getMem_free success\n");
    }
    else
    {
        printf("getMem_free error\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wanghao-boke/p/11625439.html