二维数组传二级指针错误解
二维数组不能作为二级指针参数进行传递,无法强制转换
void rotate(int** matrix, int matrixSize, int* matrixColSize);
int main()
{
int matrix[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int matrixSize = 4;
int matrixColSize = 4;
rotate(matrix, matrixSize, &matrixColSize);
return 0;
}
编译会报错类型不匹配!
二维数组传二级指针正解
可以将二维数组转换为指针数组传参给二级指针
#include <stdio.h>
#include <stdlib.h>
void rotate(int** matrix, int matrixSize, int* matrixColSize);
int main()
{
int a[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int *matrix[4] = {a[0], a[1], a[2], a[3]};
int matrixSize = 4;
int matrixColSize = 4;
rotate(matrix, matrixSize, &matrixColSize);
return 0;
}
void rotate(int** matrix, int matrixSize, int* matrixColSize){
int column = *matrixColSize;
if (matrix == NULL)
return;
for (int loop = 0; loop < matrixSize / 2; loop++) {
for (int i = loop; i < matrixSize-1-loop; i++) {
int temp = matrix[loop][i];
matrix[loop][i] = matrix[matrixSize-i-1][loop];
matrix[matrixSize-i-1][loop] = matrix[matrixSize-loop-1][matrixSize-i-1];
matrix[matrixSize-loop-1][matrixSize-i-1] = matrix[i][matrixSize-loop-1];
matrix[i][matrixSize-loop-1] = temp;
}
}
for (int i = 0; i < matrixSize; i++) {
for (int j = 0; j < matrixSize; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return;
}