i want to pass a matrix to a function in C. If i want to make the dimension of the matrix to be non-constant (eg. let the user insert by keyboard the NxM dimension) i have no problems in this. However when i try to pass this to a function i encounter some problems:
-The number of column MUST be specified in the header of the function(s) who have a matrix as parameter. If i omit this value i get:
error: array type has incomplete element type ‘int[]’ void trasposeMatrix(int M[][],int n,int m) esercizi.c:282:25: note: declaration of ‘M’ as multidimensional array must have bounds for all dimensions except the first
with this function:
void trasposeMatrix(int M[][],int n,int m)
{
int temp=0;
int M2[n][m];
printf("La matrice prima della trasposizione è: \n");
printMatrix(M,3,3);
for (int i=0;i<n;i++)
{
for (int j=0;j<m;j++)
{
M2[i][j]=M[j][i];
}
}
printf("La matrice dopo la trasposizione è: \n");
printMatrix(M2,3,3);
}
with this call:
trasposeMatrix(M,3,3);
-This value MUST be constant, otherwise if i put a parameter as value in those brackets i get this error:
esercizi.c: At top level: esercizi.c:282:29: error: ‘m’ undeclared here (not in a function) void trasposeMatrix(int M[][m],int n,int m)
with the same call and this code:
void trasposeMatrix(int M[][m],int n,int m)
{
int temp=0;
int M2[n][m];
printf("La matrice prima della trasposizione è: \n");
printMatrix(M,3,3);
for (int i=0;i<n;i++)
{
for (int j=0;j<m;j++)
{
M2[i][j]=M[j][i];
}
}
printf("La matrice dopo la trasposizione è: \n");
printMatrix(M2,3,3);
}
This can be "avoided" using constants to specify the matrix dimensions. However i don't like this kind of "constraint". Finally what if i would print a matrix via a function: what should i write in the function header if the dimesion is variable?? The function i wrote to print a matrix works well for a 3x3 matrix but what to do for 2x2 matrices and for 3x4. Maybe you got the point
Note: this things do not happen with arrays where i just write a header like:
void printArray(int a[], int dimension){}
and this works. I don't know why. Maybe is a design behaviour of C decided by his inventor, but i hope isn't because is so tediuos
Note 2: :) i'm using linux mint with gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 but with VS for Win10 i even cannot put a variable as dimension of an array :(
I'm so sorry for the very long message, but i hope to get an answer. Thanks for reading