堆区使用:
堆区注意事项:
- 如果在主函数中没有给指针分配内存,那么被调函数中需要利用高级指针给主调函数中指针分配内存。
代码示例:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int * getSpace()
{
int *p = malloc(sizeof(int*) * 5);
if (p == NULL)
{
return NULL;
}
for (int i = 0; i < 5; i++)
{
p[i] = i + 100;
}
return p;
}
void test01()
{
int*p = getSpace();
for (int i = 0; i < 5; i++)
{
printf("%d\n",p[i]);
}
free(p);
p = NULL;
}
void allocateSpace(char*pp)
{
char*temp = malloc(100);
if (temp == NULL)
{
return;
}
memset(temp,0,100);
strcpy(temp,"hello world");
pp = temp;
}
void test02()
{
char*p = NULL;
allocateSpace(p);
printf("%s\n", p);
}
void allocateSpace2(char**pp)
{
char*temp = malloc(100);
memset(temp,0,100);
strcpy(temp,"hell world");
*pp = temp;
}
void test03()
{
char*p = NULL;
allocateSpace2(&p);
printf("%s\n", p);
}
int main()
{
test03();
return EXIT_SUCCESS;
}