qfedu-c-level/day11/homework/h5.c

35 lines
919 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个程序要求用户输入一个整数n然后动态创建一个整数数组并通过循环从用户输入中读取n个整数并存储到数组中。然后使用realloc函数将数组的大小减半并打印减半后的数组内容。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("请输入一个整数: ");
scanf("%d", &n);
int *nums = (int *)malloc(n * sizeof(int *));
if (NULL == nums)
{
perror("malloc");
exit(-1);
}
printf("请输入 %d 个整数: ", n);
for (int i = 0, temp = 0; i < n; i++)
{
scanf("%d", &temp);
nums[i] = temp;
}
int halfN = n / 2; // n 的一半
nums = (int *)realloc(nums, halfN * sizeof(int *));
printf("减半后的数组内容打印如下: \n");
while (halfN--)
printf("%d ", *nums++);
printf("\n");
free(nums);
return 0;
}