1. malloc和free
void*
malloc
(
size_t
size
);
malloc和free都声明在 stdlib.h 头文件中。
![](https://img-blog.csdnimg.cn/e35e732d66504c4d818a74a5bb7ce862.png)
void Getmeoory(char** p, int num){
*p = (char*)malloc(num);
}
void Test(){
char * ptr = NULL;
Getmeoory(&ptr, 100);
strcpy(ptr, "hello");
printf(ptr);
//释放
free(ptr);
}
int main(){
Test();
return 0;
}
2.calloc
void* calloc (size_t num, size_t size);
函数的功能是为
num
个大小为
size
的元素开辟一块空间,并且把空间的每个字节初始化为
0
。
![](https://img-blog.csdnimg.cn/c71eb2db2b284a47b43ec0a5579a5161.png)
char* Getmeooy(){
char *ptr = (char*)malloc(40);
return ptr;
}
int main(){
char *ptr = NULL;
ptr = Getmeooy();
if (ptr == NULL){
printf("%s\n", strerror(errno));
}
strcpy(ptr, "hellow world");
printf(ptr);
free(ptr);
ptr = NULL;
return 0;
}
3. realloc
void*
realloc
(
void*
ptr
,
size_t
size
);
![](https://img-blog.csdnimg.cn/6dad07c81e6940c4bd3731de45de7ac7.png)
4.柔性数组
#include<string.h>
#include<errno.h>
struct st_type
{
int i;//4字节
int a[0];//柔性数组成员,也可以写int a[];
};
int main()
{
//假设我现在需要a里有10个元素
struct st_type*ps=(struct st_type*)malloc(sizeof(struct st_type) + 10 * sizeof(int));
if (ps == NULL)//由于空间可能不够开辟导致malloc开辟失败,开辟失败会返回空指针
{
printf("%s\n", strerror(errno));
return -1;//程序出问题后,跳出程序
}
//开辟成功
int j = 0;
for (j = 0;j < 10;j++)
{
ps->a[j] = j;
}
for (j = 0;j < 10;j++)
{
printf("%d ", ps->a[j]);//打印0-9
}
printf("\n");
//如果想继续用柔性数组a进行打印
//比如现在a里只有10个元素,我用完10个了,我还要继续来10个,用realloc追加
struct st_type*ptr=realloc(ps, sizeof(struct st_type) + 20 * sizeof(int));//ps:realloc第二个参数是调整后的整体大小
if (ptr == NULL)
{
printf("扩容失败\n");
return -1;
}
else
{
ps = ptr;
}
//扩容成功
int k = 0;
for (k = 10;k < 20;k++)
{
ps->a[k] = k;
}
for (j = 0;j < 20;j++)
{
printf("%d ", ps->a[j]);//打印0-19
}
//释放空间
free(ps);
ps = NULL;
return 0;
}