Passing a 2D array in a function in C program

后端 未结 3 1197
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 11:53

Below program (a toy program to pass around arrays to a function) doesn\'t compile. Please explain me, why is the compiler unable to compile(either because of techni

相关标签:
3条回答
  • 2020-12-06 12:17

    This (as usual) is explained in the c faq. In a nutshell, an array decays to a pointer only once (after it decayed, the resulting pointer won't further decay).

    An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer.

    Easiest way to solve it:

    int **array; /* and then malloc */
    
    0 讨论(0)
  • 2020-12-06 12:20

    In C99, as a simple rule for functions that receive "variable length arrays" declare the bounds first:

    void print2(int n, int m, int array[n][m]);
    

    and then your function should just work as you'd expect.

    Edit: Generally you should have a look into the order in which the dimension are specified. (and me to :)

    0 讨论(0)
  • 2020-12-06 12:28

    In your code the double pointer is not suitable to access a 2D array because it does not know its hop size i.e. number of columns. A 2D array is a contiguous allotted memory.

    The following typecast and 2D array pointer would solve the problem.

    # define COLUMN_SIZE 4
    void print2(int ** array,int n,int m)
    {
        // Create a pointer to a 2D array
        int (*ptr)[COLUMN_SIZE];
        ptr = int(*)[COLUMN_SIZE]array;
    
        int i,j;
        for(i = 0; i < n; i++)
        {
           for(j = 0; j < m; j++)
           printf("%d ", ptr[i][j]);
           printf("\n");
        }
    }
    
    0 讨论(0)
提交回复
热议问题