I would like to know how to pass a matrix of variable lines and columns to a function, transform it inside the function and them returning it in C.
Here lies the code I am trying to build to make it happen.
#include <stdio.h>
#include <stdlib.h>
void **f(int **m, int w, int h);
int main()
{
int A[3][3]={{1,2,3},{4,5, 6},{7,8,9}};
int B[3][2]={{1,2},{3, 4}, {5, 6}};
f(A, 3, 3);
f(B, 3, 2);
return 0;
}
void **f(int **m, int w, int h )
{
int i,j;
int n[w][h];
for(i=0;i<w;i++)
{
for(j=0;j<h;j++)
n[i][j] = m[i][j] + 1;
printf("%5d", m[i][j]);
}
return 0;
}
Whose compilation is returning the following errors:
main.c:20:5: warning: passing argument 1 of ‘f’ makes pointer from integer without a cast [->Wint-conversion]
main.c:13:8: note: expected ‘int **’ but argument is of type ‘int’
main.c:21:5: warning: passing argument 1 of ‘f’ makes pointer from integer without a cast [->Wint-conversion]
main.c:13:8: note: expected ‘int **’ but argument is of type ‘int’
Segmentation fault (core dumped)
Though multi-dimensional arrays have long been second-class citizens in C, modern versions give them much better support. If the array sizes are included prior to the actual array in the list of function parameters, they can form dimensions of that array. Note that A
and B
are now the last parameter to the function f()
:
void f(int w, int h, int m[w][h]);
int main()
{
int A[3][3]={{1,2,3},{4,5, 6},{7,8,9}};
int B[3][2]={{1,2},{3, 4}, {5, 6}};
f(3, 3, A);
f(3, 2, B);
return 0;
}
void f(int w, int h, int m[w][h])
{
int n[w][h];
int i, j;
for(int i;i<w;i++)
{
for(int j;j<h;j++)
n[i][j] = m[i][j] + 1;
printf("%5d", m[i][j]);
}
}
I don't recall which version of C introduced this, but for sure the int **m
parameter is incorrect because m
is not a pointer to a pointer (or an array of pointers).
It's also important that this syntax doesn't force arrays to be re-ranked according to the parameters, so if an array is [10][3]
when you define it, it ought to be [10][3]
when you describe it to a function. This is syntactic sugar for array access only.