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

58 lines
1.5 KiB
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.

// 编写一个程序要求用户输入两个整数m和n然后动态创建一个m行n列的二维整数数组。通过循环将数组的元素赋值为m行n列的连续整数。最后打印数组的内容。
#include <stdio.h>
#include <stdlib.h>
int **create_nums_arr(int m, int n)
{
// 创建二维数组
int **nums_arr = (int **)malloc(m * sizeof(int *)); // 先给二维数组分配内存,每一行的内存在下面分配
if (NULL == nums_arr)
{
perror("malloc");
exit(-1);
}
for (int i = 0; i < m; i++)
{
nums_arr[i] = (int *)malloc(n * sizeof(int *)); // 给每一行分配内存
if (NULL == nums_arr[i])
{
perror("malloc");
exit(-1);
}
}
int i = 0;
for (int j = 0; j < m; j++)
{
for (int k = 0; k < n; k++)
nums_arr[j][k] = i++; // 从 0 开始赋值
}
return nums_arr; // 返回二维数组
}
int main()
{
int m, n;
printf("请输入两个整数 m 和 n: ");
scanf("%d%d", &m, &n);
int **nums = create_nums_arr(m, n); // 创建二维数组
printf("二维数组的内容为: \n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
printf("%d ", nums[i][j]);
printf("\n");
}
// 释放内存
for (int i = 0; i < m; i++)
{
free(nums[i]); // 释放每一行的内存
}
free(nums); // 再释放二维数组的内存
return 0;
}