【C/C++语言基础学习】在主函数的定义的指针数组、二维数组通过三级指针在被调用函数分配内存...

程序的功能:在主函数中通过二维数组和指针的定义的字符串,在被调用函数中分配动态内存,并排序。
一、在主函数定义二维数组和指针数组,并初始化

int main(void)
{
    char *p[] = { "11111", "22222", "33333" };
    char str[][6] = { "aaaaa", "bbbbb", "ccccc" };
    char **p1 = NULL;

    int len1, len2, len3;
    len1 = sizeof(p)/sizeof(*p);
    len2 = 3;

    int ret = sort(p, len1, str, len2, &p1, &len3);
    for (int i = 0; i < len3; i++)
    {
        cout << p1[i] << endl;
    }
    free2(&p1, len3);//调用自定义的释放内存函数 

return 0;
system("pause");
}

二、被调用函数。在主函数的用的二级指针定义的字符串,那么在被调用函数中用三级指针接过来,先要在堆中动态分配一个二维的(len1+len2)大小的指针长度的内存,在分别分配len1大小的内存用来放字符串1的数据和len2大小的内存用来存字符串2的数据。对所有存入的数据进行排序。

int sort(char **p, int len1, char (*str)[6], int len2, char ***p1, int *len3)
{
    char** tempP = (char**)malloc(sizeof(char*)*(len1 + len2));
    if (tempP == NULL)
    {
        return -1;
    }

    int i = 0;
    int strLen = 0;
    for (; i < len1; i++)
    {
        strLen = strlen(p[i]) + 1;
        tempP[i] = (char*)malloc(sizeof(strLen));
        if (tempP[i] == NULL)
        {
            return -2;
        }
        strcpy(tempP[i], p[i]);
    }

    for (int j = 0; j < len2; j++,i++)
    {
        strLen = strlen(str[j]) + 1;
        tempP[i] = (char*)malloc(sizeof(strLen));
        if (tempP[i] == NULL)
        {
            return -3;
        }
        strcpy(tempP[i], str[j]);
    }
    //排序
    strLen = len1 + len2;
    char *myp = NULL;
    for (int x = 0; x < strLen; x++)
    {
        for (int y = x+1; y < strLen; y++)
        {
            if (strcmp(tempP[x], tempP[y])>0)
            {
                //交换指针指向,也可以用交换内容
                myp = tempP[x];
                tempP[x] = tempP[y];
                tempP[y] = myp;
            }
        }
    }
    *len3 = strLen;
    *p1 = tempP;
  
    return 0;
}

三、分配了动态内存那么就要释放内存。在主函数中调用释放内存的函数,释放内存函数如下:

void free2(char ***myp, int len)
{
    char **p = NULL;
    if (myp == NULL)
    {
        return;
    }

    p = *myp;//还原成二级指针
    if (p == NULL)
    {
        return;
    }

    for (int i = 0; i < len; i++)
    {
        free(p[i]);
    }

    free(p);
    *myp = NULL;
}

但是每次程序调用释放内存函数都会出现问题,程序会停在这个函数中。输出结果:

 

 

 

 

 

不知道是什么原因导致的,如果有大神知道还望指导一下。

 

编译环境:win7+VS2013

 

 




 

转载于:https://www.cnblogs.com/smileYangYue/p/6137643.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值