Search code examples
carrayspointersmultidimensional-arrayvariable-length-array

Passing a multidimensional array of variable size


I'm trying to understand what "best practice" (or really any practice) is for passing a multidimensional array to a function in c is. Certainly this depends on the application, so lets consider writing a function to print a 2D array of variable size. In particular, I'm interested in how one would write the function printArry(__, int a, int b) in the following code. I have omitted the first parameter as I'm not exactly sure what that should be.

void printArry(_____, int a, int b){
/* what goes here? */
}


int main(int argc, char** argv){

int a1=5;
int b1=6;
int a2=7;
int a2=8;

int arry1[a1][b1];
int arry2[a2][b2];

/* set values in arrays */

printArry(arry1, a1, b1);
printArry(arry2, a2, b2);

}

Solution

  • The easiest way is (for C99 and later)

    void printArry(int a, int b, int arr[a][b]){
        /* what goes here? */
    }
    

    But, there are other ways around

    void printArry(int a, int b, int arr[][b]){
        /* what goes here? */
    }
    

    or

    void printArry(int a, int b, int (*arr)[b]){
        /* what goes here? */
    }
    

    Compiler will adjust the first two to the third syntax. So, semantically all three are identical.

    And a little bit confusing which will work only as function prototype:

    void printArry(int a, int b, int arr[*][*]);