相信大部分程序员关于动态内存分配都比较熟悉,而动态增长内存可以实现更为便捷的内存管理。在c中realloc则可以实现这种想法。
以下是一段示例程序,将帮助你理解:
#include "stdio.h"
#include "malloc.h"
int current_element = 0;
int total_element = 2;
//session 1:动态分配内存
char *dynamic = (char *)malloc(total_element);
//session 2:realloc 重新分配内存块
void Add_element(char c){
if(current_element == total_element - 1){
total_element *= 2;
dynamic = (char *)realloc(dynamic, total_element);
//if(dynamic == NULL) error("Couldn't expand the table/n");
}
dynamic[current_element++] = c;
return ;
}
void Free_element(){
free(dynamic);
return ;
}
void Print_element(){
int i = 0;
for(i=0; i<current_element; i++){
printf("dynamic[%d] = %d/n", i, dynamic[i]);
}
return ;
}
int main(int argc, char* argv[])
{
printf("Hello World!/n");
int i = 0;
for(i=0; i<10; i++){
Add_element(i);
}
printf("size of block memory %d/n", _msize(dynamic));
printf("current elements : %d/n", current_element);
Print_element();
Free_element();
//conclusion :使用realloc可以重新分配内存,允许将内存块大小
//进行调整
return 0;
}