Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 643
ramgorur Avatar asked May 28 '15 07:05

ramgorur


People also ask

Can we allocate a 2 dimensional array dynamically?

A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.

Which function is used to created dynamic 2D arrays in C?

The malloc() function is used in c programming to store the data in the heap which is dynamic memory storage. It is mostly used for the dynamic declaration of the arrays and also be used for the creation of two-dimensional arrays.


1 Answers

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

like image 69
Mohit Jain Avatar answered Oct 11 '22 05:10

Mohit Jain