How to pass two dimensional array of an unknown size to a function

后端 未结 6 970
时光说笑
时光说笑 2020-12-14 20:49

I want to make class library, a function which its parameter is a matrix of unknown size, and the user will create his own matrix with his own size and pass it to this funct

6条回答
  •  既然无缘
    2020-12-14 21:23

    C solution:

    In C you can't omit array size (except leftmost) when passing as function parameter.

    You can write: int a[]

    but can't: int a[][]

    just for example: int a[][20]

    This constraint is here, because compiler needs to determine proper offsets for accessing array elements. However, you can make it this way:

    void print_arbitrary_2D_array(void *arr, int y, int x)
    {
        /* cast to 2D array type */
        double (*p_arr)[y][x] = (double (*)[y][x]) arr;
    
        int i, j;
    
        for (i = 0; i < y; ++i) {
            for (j = 0; j < x; ++j)
                printf(" %lf", (*p_arr)[i][j]);
            putchar('\n');
        }
    }
    
    double arr_1[4][3] = {
        { 3.3, 5.8, 2.3 },
        { 9.1, 3.2, 6.1 },
        { 1.2, 7.9, 9.4 },
        { 0.2, 9.5, 2.4 }
    };
    double arr_2[2][5] = {
        { 3.6, 1.4, 6.7, 0.1, 4.2 },
        { 8.4, 2.3, 5.9, 1.4, 8.3 }
    };
    
    print_arbitrary_2D_array(arr_1, 4, 3);
    putchar('\n');
    print_arbitrary_2D_array(arr_2, 2, 5);
    

提交回复
热议问题