您的位置:首页 > 编程语言 > C语言/C++

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

2017-02-22 20:43 856 查看
程序的功能:在主函数中通过二维数组和指针的定义的字符串,在被调用函数中分配动态内存,并排序。
一、在主函数定义二维数组和指针数组,并初始化
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
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐