例:3*3矩阵转置
将二维数组传入函数
(*val)[n],数组指针
顾名思义,就是指向数组的指针。
每个元素是一个一维数组
c语言 数组与指针 - 时空云博客 (skyw.cc)
#include "stdio.h"
void Transpose(int (*matrix)[3])
{
int tmp;
// 1,2
tmp = matrix[0][1];
matrix[0][1] = matrix[1][0];
matrix[1][0] = tmp;
// 1,3
tmp = matrix[0][2];
matrix[0][2] = matrix[2][0];
matrix[2][0] = tmp;
// 2,3
tmp = matrix[1][2];
matrix[1][2] = matrix[2][1];
matrix[2][1] = tmp;
}
int main()
{
int i, j, a[3][3];
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &a[i][j]);
}
}
Transpose(a);
for (i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ", a[i][j]);
}
printf("n");
}
return 0;
}
一级指针表示二维数组
#include <stdio.h>
#define ROW 3
#define COL 3
/* Function declarations */
void matrixInput(int* mat)
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
scanf("%d", mat + i * COL + j);
}
}
}
void matrixPrint(int* mat)
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
printf("%d ", *(mat + i * COL + j));
}
printf("n");
}
}
void matrixMultiply(int* mat1, int* mat2, int* res) {
//第一个矩阵第i行
int val;
for (int i = 0; i < ROW; i++) {
//第一个矩阵第j列
for (int j = 0; j < COL; j++) {
val = *(mat1 + i * COL + 0) * *(mat2 + 0 * COL + j) + *(mat1 + i * COL + 1) * *(mat2 + 1 * COL + j) + *(mat1 + i * COL + 2) * *(mat2 + 2 * COL + j);
*(res + i * COL + j) = val;
}
}
}
int main()
{
int mat1[ROW][COL];
int mat2[ROW][COL];
int product[ROW][COL];
/*
* Input elements in matrices.
*/
// printf("Enter elements in first matrix of size %dx%dn", ROW, COL);
matrixInput(mat1);
// printf("Enter elements in second matrix of size %dx%dn", ROW, COL);
matrixInput(mat2);
// Call function to multiply both matrices
matrixMultiply(mat1, mat2, product);
// Print product of both matrix
matrixPrint(product);
return 0;
}