炒了个栗子
#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\n"); exit(1); } int i; for(i=0;i<N1;i++){ ip[i] = i; printf("ip[%d] = %d\t", i, ip[i]); } printf("\n"); large_ip = (int *)realloc(ip,N2*sizeof(int)); if(large_ip == NULL){ printf("memory allocated failed!\n"); exit(1); } for(i=N1;i<N2;i++){ large_ip[i]=9; } for(i=0;i<N2;i++){ printf("large_ip[%d] = %d\t", i, large_ip[i]); } printf("\n"); small_ip = (int *)realloc(large_ip,N3*sizeof(int)); if(small_ip == NULL){ printf("memory allocated failed!\n"); exit(1); } for(i=0;i<N3;i++){ printf("small_ip[%d] = %d\t", i, small_ip[i]); } printf("\n"); ////手动释放内存 free(small_ip); return 0; }
时间: 2024-11-14 11:03:11