Search code examples
carraysfunctiongcc4.7

how to write a c function that can take both dynamic/statically allocated 2D array?


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?


Solution

  • Your dynamic allocation for 2d array is not correct. Use it as:

    double (*m1)[3] = malloc(sizeof(double[3][3]));
    

    And then it will work.

    Moreover change the function prototype to:

    void func(double m[][3], int dim)
    

    Another way is to use a 1-D array of size w * h instead of 2-D array.

    Working example


    From comment of @TheParamagneticCroissant c99 onwards, you can also VLA's and make both your dimensions variable. (You'll need to allocate the 2D array properly though)

    Change function signature to:

    void func(int dim, double[dim][dim]);  /* Second arg is VLA whose dimension is first arg */
    /* dim argument must come before the array argument */
    

    Working example