您的位置:首页 > 其它

指针数组堆上分配内存(动态分配内存)

2016-10-10 23:04 190 查看
#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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: