1.创建二维数组
int** create(const int row, const int col) {
/*根据参数row和col,创建一个矩阵,返回指针*/
int** matrix = (int**)malloc(sizeof(int*) * row);
for (int i = 0; i < row; i++) {
matrix[i] = (int*)malloc(sizeof(int) * col);
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &(matrix[i][j]));
}
}
return matrix;
}
2.遍历二维数组
void traverse(int** matrix, const int row, const int col) {
/*遍历二维数组matrix*/
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
3.销毁二维数组
void destroy(int** matrix, const int row) {
/*释放二维数组matrix占用的堆内存*/
int i = 0;
while (i < row) {
free(matrix[i]);
matrix[i] = NULL;
i++;
}
free(matrix);
matrix = NULL;
}
4.完整代码
点击查看代码
#include <stdio.h>
#include <stdlib.h>
int** create(const int row, const int col);
void traverse(int** matrix, const int row, const int col);
void destroy(int** matrix, const int row);
int main(int argc, char* argv[]) {
/*二级指针指向一个二维数组*/
int row, col;
scanf("%d %d", &row, &col);
/*创建,遍历,销毁二维数组*/
int** matrix = create(row, col);
traverse(matrix, row, col);
destroy(matrix, row);
matrix = NULL;
return 0;
}
int** create(const int row, const int col) {
/*根据参数row和col,创建一个矩阵,返回指针*/
int** matrix = (int**)malloc(sizeof(int*) * row);
for (int i = 0; i < row; i++) {
matrix[i] = (int*)malloc(sizeof(int) * col);
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &(matrix[i][j]));
}
}
return matrix;
}
void traverse(int** matrix, const int row, const int col) {
/*遍历二维数组matrix*/
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
void destroy(int** matrix, const int row) {
/*释放二维数组matrix占用的堆内存*/
int i = 0;
while (i < row) {
free(matrix[i]);
matrix[i] = NULL;
i++;
}
free(matrix);
matrix = NULL;
}