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

35 lines
773 B
C
Raw 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的整数数组并通过循环将数组的元素赋值为1到n的连续整数。最后打印数组的内容。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *create_arr(int n)
{
int *p = (int *)malloc(n * sizeof(int *));
if (NULL == p)
{
perror("malloc");
exit(0);
}
memset(p, 0, n * sizeof(int *)); // 设定初始值为 0
int i = 0;
for (; i < n; i++)
*(p + i) = i + 1;
return p;
}
int main()
{
int n;
printf("请输入一个整数: ");
scanf("%d", &n);
int *nums = create_arr(n);
while (*nums)
printf("%d ", *(nums++));
printf("\n");
free(nums);
return 0;
}