51.动态内存管理
1.malloc
#include <stdio.h>
#include <malloc.h>
int main()
{
int len;
int i,b;
int * p = (int *)malloc(4 * len);
printf("请输入数组个数:");
scanf("%d",&len);
printf("请输入要存储的数字:");
for( i=0;i<len;i++){
scanf("%d",&p[i]);
}
for( b=0;b<len;b++){
printf("%d\n",p[b]);
}
free(p);
return 0;
}
2.calloc
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
int i;
int *p = (int *)calloc(10, sizeof(int));
for (i = 0; i < 10; i++)
{
printf("%3d", p[i]);
}
printf("\n");
free(p);
getch();
return 0;
}
3.realloc
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str;
/* 最初的内存分配 */
str = (char *)malloc(15);
strcpy(str, "runoob");
printf("String = %s, Address = %u\n", str, str);
/* 重新分配内存 */
str = (char *)realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}