C //例 7.13 有一个3*4的矩阵,求所有元素中的最大值。

C程序设计 (第四版) 谭浩强 例 7.13

例 7.13 有一个3*4的矩阵,求所有元素中的最大值。

IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法:使用指针、动态分配内存
c 复制代码
#include <stdio.h>
#include <stdlib.h>

#define M 3
#define N 4

void initialMatrix(int ***matrix, int m, int n){
	*matrix = (int**)malloc(m * sizeof(int*));
	for(int i = 0; i < m; i++){
		(*matrix)[i] = (int*)malloc(n * sizeof(int));
	}
}

void inputMatrix(int **matrix, int m, int n){
	printf("Enter %d*%d matrix:\n", m, n);
	for(int i = 0; i < m; i++){
		for(int j = 0; j < n; j++){
			scanf("%d", &matrix[i][j]);
		}
	}
}

int max(int **matrix, int m, int n){
	int max = matrix[0][0];
	for(int i = 0; i < m; i++){
		for(int j = 0; j < n; j++){
			if(matrix[i][j] > max){
				max = matrix[i][j];
			}
		}
	}
	return max;
}

void outputMatrix(int **matrix, int m, int n, int max(int **, int, int)){
	printf("Max Value in the matrix is %d\n", max(matrix, m, n));
}

void freeMatrix(int ***matrix, int m){
	for(int i = 0; i < m; i++){
		free((*matrix)[i]);
	}
	free(*matrix);
}

int main(){
	int **matrix = NULL;

	initialMatrix(&matrix, M, N);
	inputMatrix(matrix, M, N);
	outputMatrix(matrix, M, N, max);
	freeMatrix(&matrix, M);

	system("pause");
	return 0;
}
相关推荐
IT方大同15 小时前
C语言的组成部分
c语言·开发语言
高洁0116 小时前
具身智能-普通LLM智能体与具身智能:从语言理解到自主行动 (2)
深度学习·算法·aigc·transformer·知识图谱
l1t16 小时前
使用DuckDB SQL求解Advent of Code 2024第9题 磁盘碎片整理
数据库·sql·算法·duckdb·advent of code
用户0435437719516 小时前
C语言:数组入门及其基础算法详解
c语言
say_fall16 小时前
WinAPI 极简教程:超简单的 Windows 接口入门
c语言·windows
小南家的青蛙16 小时前
LeetCode面试题 04.06 后继者
算法·leetcode·职场和发展
IT·小灰灰16 小时前
基于Python的机器学习/数据分析环境搭建完全指南
开发语言·人工智能·python·算法·机器学习·数据分析
wefg117 小时前
【C++】智能指针
开发语言·c++·算法
搂鱼11451417 小时前
一类判断包含颜色整体的题目
算法
Demon--hx17 小时前
[c++]string的三种遍历方式
开发语言·c++·算法