malloxc,calloc,realloc ,free
1.头文件:#include <stdlib.h>
2.原则:谁申请谁释放
3.返回值:三个申请返回值都是 void * ,void*是百搭的,可以是char*也可以是int*
4.申请:
malloc (size_t size);//申请一个多大的空间
calloc (size_t nmemb, size_t size);//申请指定要多少个多大的空间
realloc(void *ptr, size_t size);//重新分配已经被分配的
5.释放:
Free(void *ptr);
我们释放指向空间的指针时,还应让指针直指向空。
Int *p = malloc(sizeof(int));
…..
Free(p);
P =NULL;
动态数组
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
int num =5;
int i;
p = malloc(sizeof(int)*num);
for(i = 0;i<num;i++)
scanf("%d",&p[i]);
for(i=0;i<num;i++)
printf("%d",p[i]);
printf("\n");
exit(0);
}
找错误并修改:
#include <stdio.h>
#include <stdlib.h>
void func(int *p, int n)
{
p = malloc(n);
if(p==NULL)
exit(1);
return;
}
int main()
{
int num = 100;
int *p =NULL;
func(p,num);
free(p);
exit(0);
}
//因为函数中使用了malloc所以是错的,如果不用malloc那就是对的。
修改1:
void func(int **p, int n)//二级指针,指向指针的地址,
{
*p = malloc(n); //*p相当于main函数中的p
if(*p==NULL)
exit(1);
return;
}
int main()
{
int num = 100;
int *p =NULL;
func(&p,num);//传输指针的地址
free(p);
exit(0);
}
修改2:
void *func(int *p, int n)//返回值设为指针类型
{
p = malloc(n);
if(p==NULL)
exit(1);
return p ;//返回指针
}
Int main()
{
p=func(p,num);//接收函数的返回值
}