Search code examples
arrayscfunctionpointersfunction-pointers

2d array pointer used in function


im writting a program in which i want to use this piece of code to transfer a 2d array in a function, but i dont understand fully how it works exactly. Can someone explain it, specifically line 7?


#include <stdio.h>
void print(int *arr, int m, int n)
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", *((arr+i*n) + j));
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
 
    // We can also use "print(&arr[0][0], m, n);"
    print((int *)arr, m, n);
    return 0;
}

i also tried using

*( *(p + i) + j)

instead, but it didnt really work and i dont know why so if someone can explain why this didnt work as well i would really appreciate it.


Solution

  • In modern C, you should use Variable Length Array types introduced in C99.

    void print(int m, int n, int arr[m][n])
    {
        int i, j;
        for (i = 0; i < m; i++)
          for (j = 0; j < n; j++)
            printf("%d ", arr[i][j]);
    }
    

    The function should be called with a simple:

    int main()
    {
        int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int m = 3, n = 3;
     
        print(m, n, arr);
        return 0;
    }
    

    The VLA types are optional feature in C11 but they will be mandatory again in C23.