malloc(size_t size):向内存空间申请指定大小的内存,并把该申请的内存以指针的形式返回
#include <stdio.h>
#include <stdlib.h>
#define MAX(X,Y) (X>Y?X:Y)
#include <math.h>
struct S
{
int a;
char* b;
};
int main()
{
struct S* ps = malloc(sizeof(struct S));//申请结构体大小的内存,并把结构体指针指向该内存
printf("%d\n",sizeof(struct S));//8个字节
ps->a = 100;//通过指针给成员赋值
ps->b = "hello word";
printf("%s\n",ps->b);
printf("%p\n",ps);//打印指针指向的地址,也就是结构体的起始地址
printf("%p\n",ps->b);
printf("%p\n",&(ps->a));//打印成员a的地址,显示就是结构体的起始地址
return 0;
}
cmalloc(size,size_t):向内存申请size_t个,size大小的内存空间,它会把这段内存空间全部初始化为0,然后以指针的形式返回该地址.
#include <stdio.h>
#include <stdlib.h>
#define MAX(X,Y) (X>Y?X:Y)
#include <math.h>
struct S
{
int a;
char* b;
};
int main()
{
struct S* ps = calloc(sizeof(struct S),2);//申请2个结构体大小的内存空间,16字节
printf("%d\n",sizeof(struct S));//8字节
ps->a = 100;
ps->b = "hello word";
printf("%s\n",ps->b);
printf("%p\n",ps);
printf("%p\n",ps->b);
printf("%p\n",&(ps->a));
free(ps);//释放内存
return 0;
}
最上面16个字节,全部为零
realloc():给已经申请的内存,重新定义大小,并返回一个新的指针,这个指针有可能和原指针相同,取决于再次申请内存的大小.如果是一个新的指针,它会把前面指针对应的数据全部复制到新的内存里面.
#include <stdio.h>
#include <stdlib.h>
#define MAX(X,Y) (X>Y?X:Y)
#include <math.h>
struct S
{
int a;
char* b;
};
int main()
{
struct S* ps = calloc(sizeof(struct S),2);
struct s* ptr = realloc(ps,24);
printf("%d\n",sizeof(struct S));
ps->a = 100;
ps->b = "hello word";
printf("%s\n",ps->b);
printf("%p\n",ps);
printf("%p\n",ps->b);
printf("%p\n",&(ps->a));
return 0;
}
两个指针相同,只是在PS的后面加了8个字节
#include <stdio.h>
#include <stdlib.h>
#define MAX(X,Y) (X>Y?X:Y)
#include <math.h>
struct S
{
int a;
char* b;
};
int main()
{
struct S* ps = calloc(sizeof(struct S),2);
struct s* ptr = realloc(ps,240000);//把申请内存加大到一定程度
printf("%d\n",sizeof(struct S));
ps->a = 100;
ps->b = "hello word";
printf("%s\n",ps->b);
printf("%p\n",ps);
printf("%p\n",ps->b);
printf("%p\n",&(ps->a));
return 0;
}
这里两个指针就不相同了