以下代码:
#include <stdio.h>
void printSpiral(int **M, int row1, int row2, int col1, int col2) {
if (!((row1 <= row2) && (col1 <= col2)))
return;
int i;
for (i = col1; i <= col2; i++)
printf("%d ", M[row1][i]);
for (i = row1; i <= row2; i++)
printf("%d ", M[i][col2]);
for (i = col2; i >= col1; i--)
printf("%d ",M[row2][i]);
for (i = row2; i >= row1; i--)
printf("%d ",M[i][col1]);
printSpiral(M,row1+1,row2-2,col1+1,col2-1);
}
int main() {
int n;
scanf("%d",&n);
int M[n][n];
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d",&M[i][j]);
printSpiral(M,0,n-1,0,n-1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
发出以下警告:
spiral.c: In function ‘main’:
spiral.c:26:3: warning: passing argument 1 of ‘printSpiral’ from incompatible pointer
type [enabled by default]
printSpiral(M,0,n-1,0,n-1);`
spiral.c:3:6: note: `expected ‘int **’ but argument is of type ‘int (*)[(sizetype)(n)]’`
void printSpiral(int **M, int row1, int row2, int col1, int col2) {
Run Code Online (Sandbox Code Playgroud)
我第一次看到这个警告.这是什么意思?
hac*_*cks 12
这段代码有两个问题.首先,你传递的参数int (*)[(sizetype)(n)](指向一个n整数数组的指针,这是你的2D数组M在传递给函数时衰减的类型)到你期望参数的函数int **.永远记住数组不是指针.一种可能的解决方案是您可以将函数的第一个参数更改为int (*)[(sizetype)(n)]type.
void printSpiral(int (*M)[n], int row1, int row2, int col1, int col2) {
Run Code Online (Sandbox Code Playgroud)
但是通过这样做,第二个问题将会出现,因为你声明M为可变长度数组,并且n函数不知道.这个问题可以通过将解决n从main你的函数,因此你的函数定义修改为
void printSpiral(int n, int (*M)[n], int row1, int row2, int col1, int col2) {
Run Code Online (Sandbox Code Playgroud)