一、代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//释放内存空间
void freeMem(char** p2, int num)
{
int i = 0;
char** tmp = p2;
if (tmp == NULL)
{
return;
}
for (i = 0; i < num; i++)
{
//先释放一级指针
if (tmp[i] != NULL)
{
free(tmp[i]);
}
}
if (tmp != NULL)
{
//再释放二级指针
free(tmp);
}
}
//打造堆区内存空间
int getMem(char*** p3, int* nCount)
{
int ret = 0;
int i = 0;
int num = 3;
char** tmp = NULL;
//下面malloc内存相当于一个指针数组
tmp = (char**)malloc(num * sizeof(char*));//====> char* tmp[num].
if (tmp == NULL)
{
ret = -1;
printf("func getMem() malloc1 error:%d\n", ret);
/*return ret;*/
goto END;
}
//分配内存空间之后初始化
memset(tmp, 0, num * sizeof(char*));
for (i = 0; i < num; i++)
{
tmp[i] = (char*)malloc(16);
if (tmp[i] == NULL)
{
ret = -2;
printf("func getMem() malloc2 error:%d\n", ret);
/*return ret;*/
goto END;
}
//分配内存空间之后初始化
memset(tmp[i], 0, 16);
}
END:
if (ret != 0)
{
freeMem(tmp, num);
}
else
{
*nCount = num;
*p3 = tmp;
}
return ret;
}
//给内存空间赋值
void set_value(char** pt2, int num)
{
int i = 0;
if (pt2 == NULL)
{
printf("func ser_value() error\n");
return;
}
char** tmp = pt2;
for (i = 0; i < num; i++)
{
sprintf(tmp[i], "%d%d%d", i, i, i);
}
}
//print
void printValue(char** pt2, int num)
{
int i = 0;
for (i = 0; i < num; i++)
{
printf("%s\n", pt2[i]);
}
}
//sort
void sort_value(char** pt2, int num)
{
int i = 0, j = 0;
char** tmp = pt2;
char* cp = NULL;
for (i = 0; i < num; i++)
{
for (j = 0; j < num; j++)
{
if (strcmp(tmp[i], tmp[j]) > 0)
{
cp = tmp[i];
tmp[i] = tmp[j];
tmp[j] = cp;
}
}
}
}
//手动打造内存模型
int main()
{
int ret = 0;
char** p1 = NULL;
int num = 0;
//getMem
ret = getMem(&p1, &num);
if (ret != 0)
{
printf("func getMem() error:%d\n", ret);
return ret;
}
//set value
set_value(p1, num);
//print
printf("sort before:\n");
printValue(p1, num);
//sort
sort_value(p1, num);
//print
printf("sort after:\n");
printValue(p1, num);
printf("\n");
system("pause");
return 0;
}
二、内存模型图: