Passing a multidimensional array of variable size

前端 未结 2 1812
鱼传尺愫
鱼传尺愫 2020-12-03 07:58

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 applic

相关标签:
2条回答
  • 2020-12-03 08:39

    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[*][*]);
    
    0 讨论(0)
  • 2020-12-03 08:57

    This is not really an answer, but extended comment to the OP's comment question, "well you can pass the array without knowing the number of rows with this, but then how will you know when to stop printing rows?"

    Answer: generally, you can't, without passing the array size too. Look at this 1-D example, which breaks the array size.

    #include <stdio.h>
    
    int procarr(int array[16], int index)
    {
       return array[index];
    }
    
    int main (void)
    {
        int arr[16] = {0};
        printf("%d\n", procarr(arr, 100));
        return 0;
    }
    

    Program output (although all elements initialised to 0):

    768
    

    That was undefined behaviour and there was no compiler warning. C does not provide any array overrun protection, except for array definition initialisers (although such initialisers can define the array length). You have to pass the array size too, as in

    #include <stdio.h>
    
    int procarr(int array[16], size_t index, size_t size)
    {
        if (index < size)
            return array[index];
        return -1;                  // or other action / flag
    }
    
    int main (void)
    {
        int arr[16] = {0};
        printf("%d\n", procarr(arr, 100, sizeof arr / sizeof arr[0]));
        return 0;
    }
    

    Program output:

    -1
    
    0 讨论(0)
提交回复
热议问题