Following code:
#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;
}
gives following warning:
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) {
I have seen this warning for the first time. What does it mean?
There are two problems with this code. First you are passing argument of int (*)[(sizetype)(n)]
(pointer to an array of n
integers, this is the type your 2D array M
decays to when you pass it to a function) to your function which is expecting an argument of int **
. Always remember Arrays are not pointers. One possible solution is you can change your function's first parameter to int (*)[(sizetype)(n)]
type.
void printSpiral(int (*M)[n], int row1, int row2, int col1, int col2) {
But by doing this the second problem will comes into light and that is because of you declared M
as variable length array and n
is not known to the function. This issue can be resolved by passing n
from main
to your function and hence change your function definition to
void printSpiral(int n, int (*M)[n], int row1, int row2, int col1, int col2) {
The compiler wants to tell you that the functions expects a int **
, but you provide it an argument of type int (*)[(sizetype)(n)]
.
The first is a pointer to (the first element of an array of) int *
, the second one is a pointer to an array/arrays of given length.
Compare what both means in memory and why this cannot work this way.
The solution would be to provide the function a pointer to one element an at least the total number of columns. (If you want the function to do bounds-checking, it needs the number of rows as well.) Then you have to calculate the indexes manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With