#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **allocateSpace(int len)
{
if (len <= 0)
{
return NULL;
}
char **temp = (char **)malloc(sizeof(char *)*len);
if (temp == NULL)
{
return NULL;
}
memset(temp, 0, sizeof(char *)*len);
for (int i = 0; i < len; i++)
{
temp[i] = (char *)malloc(100);
if (temp[i] == NULL)
{
goto End;
}
memset(temp[i], 0, 100);
sprintf(temp[i], "%2d_hello world!", i + 1);
}
return temp;
End:
for (int i=0;i<len;i++)
{
if (temp[i] != NULL)
{
free(temp[i]);
temp[i] = NULL;
}
}
free(temp);
temp = NULL;
return NULL;
}
void freeAll(char **str, int len)
{
if (str == NULL)
{
return;
}
for (int i = 0; i<len; i++)
{
if (str[i] != NULL)
{
free(str[i]);
str[i] = NULL;
}
}
free(str);
str = NULL;
}
void test()
{
char **p = NULL;
p = allocateSpace(10);
for (int i = 0; i < 10; i++)
{
printf("%s\n", p[i]);
}
freeAll(p, 10);
}
void main()
{
test();
system("pause");
}
指针数组堆上分配内存(动态分配内存)
最新推荐文章于 2023-03-18 07:00:00 发布