In my main function, I allocate a 2D contiguous array with equal number of rows and columns that are decided by the user:
#include <stdio.h>
#include <stdlib.h>
int main() {
int d=0;
scanf("%d", &d);
int(*matrix)[d]= malloc(d*sizeof(*matrix));
}
I then want to pass this matrix and the d value to a function that will fill it with numbers from 1 to d*d and then print it:
void fillMatrix(int d, /*matrix*/)
How should I pass the matrix to the function? I don't have trouble with the rest of the function per se, but I don't seem to be able to properly pass the matrix in order to then fill it as a generic 2d array with the line array[i][j]= value. From what CLion is telling me, I seem to be working wrong with the fact that it's a int(*)[d], as it often tells me that I'm passing an incompatible pointer when I try to actually call the function.
Some things I tried and didn't work:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix(int, int*);
int main() {
int d=0;
scanf("%d", &d);
int(*matrix)[d]= malloc(d*sizeof(*matrix));
fillMatrix(d, (int *) matrix);
}
void fillMatrix(int d, int *matrix){
int i=0, j=0, k=1;
for(i=0;i<d;i++){
for(j=0;j<d;j++){
matrix[i][j]= k;
k++;
}
}
}
Here, when I try to do matrix[i][j]= k;
, I get the error "Subscripted value is not an array, pointer, or vector ", and changing matrix to *matrix doesn't help
#include <stdio.h> #include <stdlib.h>
void fillMatrix(int, int*);
int main() {
int d=0;
scanf("%d", &d);
int(*matrix)[d]= malloc(d*sizeof(*matrix));
fillMatrix(d, matrix);
}
Here, when calling the function, I get the error "Incompatible pointer types passing 'int (*)[d]' to parameter of type 'int *' "
And when I try to write void fillMatrix(int, int[][]);
, I get the error "Array has incomplete element type 'int []' "
Finally, if I do:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix(int, int[][0]);
int main() {
int d=0;
scanf("%d", &d);
int(*matrix)[d]= malloc(d*sizeof(*matrix));
fillMatrix(d, matrix);
}
void fillMatrix(int d, int matrix[][0]){
int i=0, j=0, k=1;
for(i=0;i<d;i++){
for(j=0;j<d;j++){
matrix[i][j]= k;
k++;
}
}
for(i=0;i<d;i++){
for(j=0;j<d;j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
it won't print the proper k value.