Question

I want to do this but it doesn't work. Is it possible to do it or do I have to declare A as double pointer float**? Note that I need an universal function for various array dimensions so I can't change the function arguments.

void func(float** arr, int x, int y){
    //access to arr[0][0] for e.g. causes SEGFAULT
}
...
float A[2][2]={{1,0},{0,1}};
func(A, 2, 2);
Was it helpful?

Solution

To pass 2D array to function you need to know at least element count in 2nd dimension at compilation time.

void func(float arr[][2], int n)

If you don't know the size of array at compile time there isn't much you can do except:

void func(float *arr, int n, int m)
{
    // getting arr[i][j] with arr[i*m + j]
}

float A[2][2]={{1,0},{0,1}};
func(&A[0][0], 2, 2);

OTHER TIPS

Change the declaration of func() to:

void func(float arr[2][2], int x, int y)
{
}

For futher reading see this answer: How to pass 2D array (matrix) in a function in C?

A 2d array is NOT equivalent to **. As a rule, you can strip off one "layer" of indirection any replace it with []. Thus something like float *A[] is equivalent to float **A. Note you can also only have one array dimension having undefined size; thus float[2][] is ok, while float[][] is not.

You'll need to change your func to something like void func(float *arr[2], ...) or void func(float arr[2][], ...).

If generality is your concern, you need to make it work like this:

 void func(int** arr, int x, int y)
{
}

int main()
{
  int rows, cols, i;
  int **arr;

  arr = (int**)malloc(rows * sizeof(int*));
  for (i=0; i<rows; i++)
  {
    arr[i] = (int*)malloc(cols * sizeof(int));
  }
  arr[0][0]=1;arr[1][0]=0;arr[0][1]=0;arr[0][1]=1;
  func(arr, rows, cols);

  for (i=0; i<rows; i++)
  {
    free(arr[i]);
  }
  free(arr);
}

If you have a modern C compiler, starting with C99, you may simply do

void func(size_t x, size_t y, float arr[x][y]) {
 // something using arr[i][j] naturally
}

The only restriction is that the sizes must come before they are used in the parameter list.

On the call side you then can use something like the following to avoid allocating a dynamic matrix as auto variable:

float (*A)[x0] = malloc(sizeof(float[x0][y0]);
...
func(x0, y0, A);
...
free(A)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top