炒了个栗子
#include <stdio.h> #define N1 (5) #define N2 (7) #define N3 (3) int main(){ int *ip; int *large_ip; int *small_ip; //内存空间的首地址 ip = (int *)malloc(N1*sizeof(int)); if(ip == NULL){ printf("memory allocated failed "); exit(1); } int i; for(i=0;i<N1;i++){ ip[i] = i; printf("ip[%d] = %d ", i, ip[i]); } printf(" "); large_ip = (int *)realloc(ip,N2*sizeof(int)); if(large_ip == NULL){ printf("memory allocated failed! "); exit(1); } for(i=N1;i<N2;i++){ large_ip[i]=9; } for(i=0;i<N2;i++){ printf("large_ip[%d] = %d ", i, large_ip[i]); } printf(" "); small_ip = (int *)realloc(large_ip,N3*sizeof(int)); if(small_ip == NULL){ printf("memory allocated failed! "); exit(1); } for(i=0;i<N3;i++){ printf("small_ip[%d] = %d ", i, small_ip[i]); } printf(" "); ////手动释放内存 free(small_ip); return 0; }