I have a function that supposed to take 2D array as an argument, my code looks like this --
#include <stdio.h>
#include <stdlib.h>
void func(double**, int);
int main()
{
double m[3][3] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
func(m, 3);
}
void func(double **m, int dim)
{
int i, j ;
for(i = 0 ; i < dim ; i++)
{
for(j = 0 ; j < dim ; j++)
printf("%0.2f ", m[i][j]);
printf("\n");
}
}
Then the compiler says --
test.c: In function ‘main’:
test.c:9:2: warning: passing argument 1 of ‘func’ from incompatible pointer type [enabled by default]
func(m, 3);
^
test.c:4:6: note: expected ‘double **’ but argument is of type ‘double (*)[3]’
void func(double**, int);
^
But when I say --
int main()
{
int i, j;
double m[3][3] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
double **m1 ;
m1 = (double**)malloc(sizeof(double*) * 3);
for(i = 0 ; i < 3 ; i++)
{
m1[i] = (double*)malloc(sizeof(double) * 3);
for(j = 0 ; j < 3 ; j++)
m1[i][j] = m[i][j] ;
}
func(m1, 3);
for(i = 0 ; i < 3 ; i++) free(m1[i]);
free(m1);
}
It compiles and runs.
Is there any way I can make func()
to take both the statically/dynamically defined 2D array ? I am confused since I am passing the pointer m
, why it is not correct for the first case ?
does it mean that I need to write two separate functions for two different types of arguments?