#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//通过函数返回值返回开辟的内存首地址
char **getMem(int num)
{
int i = 0;
char **p2 = NULL;
p2 = (char **)malloc(sizeof(char *) * num);
if (p2 == NULL)
{
return NULL;
}
for (i=0; i<num; i++)
{
p2[i] = (char *)malloc(sizeof(char) * 100 ); //char buf[100];
sprintf(p2[i], "%d%d%d", i+1, i+1, i+1);
}
return p2;
}
//通过三级指针动态打造二维数组
int getMem1(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 -2;
}
for (i=0; i<num; i++)
{
tmp[i] = (char *)malloc(sizeof(char) * 100 ); //char buf[100];
sprintf(tmp[i], "%d%d%d", i+1, i+1, i+1);
}
*p3 = tmp; //间接赋值是指针存在的最大意义
return 0;
}
void getMem_Free(char ***p3 , int num)
{
int i = 0;
char **tmp = NULL;
if (p3 == NULL)
{
return ;
}
tmp = *p3;
for (i=0; i<num; i++)
{
free(tmp[i]);
}
free(tmp);
*p3 = NULL; //把实参赋值成null
}
int main(int argc, const char * argv[])
{
int i = 0, j = 0;
char **p2 = NULL;
int num = 5;
char *tmp = NULL;
char tmpbuf[100];
p2 = getMem(num);
for (i=0; i<num; i++)
{
printf("%s \n", p2[i]);
}
getMem_Free(&p2, num);
puts("888888888888888888888888888888888888888888");
getMem1(&p2, num);
for (i=0; i<num; i++)
{
printf("%s \n", p2[i]);
}
getMem_Free(&p2, num);
return 0;
}
C二级指针分配内存方式与释放
最新推荐文章于 2024-06-26 19:37:24 发布