How Pointer of Multi-Dimension Arrays Work in C

后端 未结 3 680
星月不相逢
星月不相逢 2020-12-10 08:40

I\'m experimenting with the concept of pointer to multi-dimension array in C. Suppose I want to process a multi-dimensional array via a function. The code kinda looks like t

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 09:08

    You have a type mismatch. Given the declaration int array[10][10], the type of the expression &array will be int (*)[10][10], not int ***. If you change your function prototype to read

    void proc_arr(int (*array)[10][10])
    

    then your code should work as written.

    The following table shows the types for various array expressions given a particular declaration.

    Declaration: T a[M]; 
    
    Expression      Type               Decays To        
    ----------      ----               ---------        
             a      T [M]              T *              
            &a      T (*)[M]                   
    
            *a      T                           
          a[i]      T                           
    
    Declaration: T a[M][N]; 
    
    Expression      Type               Decays To        
    ----------      ----               ---------        
             a      T [M][N]           T (*)[N]         
            &a      T(*)[M][N]
            *a      T [N]              T *
           a[i]     T [N]              T *
          &a[i]     T (*)[N]
          *a[i]     T 
        a[i][j]     T
    
    Declaration: T a[M][N][O]; 
    
    Expression      Type               Decays To        
    ----------      ----               ---------        
             a      T [M][N][O]        T (*)[N][O]
            &a      T (*)[M][N][O]     
            *a      T [N][O]           T (*)[O]
          a[i]      T [N][O]           T (*)[O]
         &a[i]      T (*)[N][O]     
         *a[i]      T [N]              T *
       a[i][j]      T [N]              T *
      &a[i][j]      T (*)[N]
      *a[i][j]      T
    a[i][j][k]      T
    

    The pattern for higher-dimensioned arrays should be clear.

提交回复
热议问题