C的申请内存的库函数除了malloc,还有realloc calloc,其中reaclloc还可以动态的进行扩展内存大小,省去了自己实现,以前没太注意,都是自己手写扩容的,狗头
1:calloc()
头文件:stdlib.h
声明:void *calloc(int n, int size);
含义:在堆上,分配n*size个字节,并初始化为0,返回void* 类型
返回值:同malloc() 函数
2:recalloc()
头文件:stdlib.h
声明:void * realloc(void * p,int n);
含义:重新分配堆上的void指针p所指的空间为n个字节,同时会复制原有内容到新分配的堆上存储空间。注意,若原来的void指针p在堆上的空间不大于n个字节,则保持不变。
返回值:同malloc() 函数
测试程序:
#include <iostream>
#include <array>
#include <stdlib.h>
int main(int argc, char* argv[])
{
/*unsigned char candata[4] = {0x44, 0xFE, 0x23, 0x81};
printf("%02x %02x %02x %02x\n", candata[0], candata[1], candata[2], candata[3]);
can_data_assignment(candata,31,14,4);
unsigned int c = can_data_transfer_signal();
can_data_free();
printf("%d\n", c);*/
int* p1 = 0;
int* p2 = 0;
int* p3 = 0;
int i = 0;
p1 = (int*)calloc(5,sizeof(int));
p2 = (int*)malloc(5*sizeof(int));
p3 = (int*)malloc(5 * sizeof(int));
printf("p1 content\n");
for (i = 0; i < 5; ++i)
{
printf("%ld", p1[i]);
}
printf("\n");
printf("p2 content\n");
for (i = 0; i < 5; ++i)
{
printf("%ld",p2[i]);
}
printf("\n");
for (i = 0; i < 5; ++i)
{
p3[i] = i;
}
printf("\n");
p3 = (int*)realloc(p3,10 * sizeof(int));
for (i = 0; i < 10; ++i)
{
printf("%ld", p3[i]);
}
system("pause");
return 0;
}
运行结果: