intmain(){ int num; printf("please insert the count of the number: \n");
scanf("%d", &num);
int *arr = (int *) malloc(sizeof(int) * num);
for (int i = 0; i < num; ++i) { int insert_num; printf("please insert No.%d :", (i + 1)); scanf("%d", &insert_num); arr[i] = insert_num; // *(arr + i) == arr[i] } for (int i = 0; i < num; ++i) { printf("your number is: %d , the addr: %p\n", *(arr + i), arr + i); }
// 在原基础上新增加空间 printf("please insert the count of the new memory: \n"); int newMem; scanf("%d", &newMem);
// realloc第一个参数传入指针是为了防止分配内存不够时,系统会重新开辟一个连续的空间,然后把以前地址(arr)的数据拷贝过来。 int *newArr = (int *) realloc(arr, sizeof(int) * (num + newMem)); if (newArr) { for (int i = num; i < num + newMem; ++i) { int insert_num; printf("please insert No.%d :", (i + 1)); scanf("%d", &insert_num); newArr[i] = insert_num; } for (int i = 0; i < num + newMem; ++i) { printf("your number is: %d , the addr: %p\n", *(newArr + i), newArr + i); } }