Passing a multidimensional array of variable size

前端 未结 2 1841
鱼传尺愫
鱼传尺愫 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: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 
    
    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 
    
    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
    

提交回复
热议问题