Pass By Reference Multidimensional Array With Unknown Size

前端 未结 5 539
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 10:36

How to pass by reference multidimensional array with unknown size in C or C++?

EDIT:

For example, in main function I have:

int main(){
    int          


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 10:54

    H2CO3's solution will work for C99 or a C2011 compiler that supports VLAs. For C89 or a C2011 compiler that doesn't support VLAs, or (God forbid) a K&R C compiler, you'd have to do something else.

    Assuming you're passing a contiguously allocated array, you can pass a pointer to the first element (&a[0][0]) along with the dimension sizes, and then treat it as a 1-D array, mapping indices like so:

    void foo( int *a, size_t rows, size_t cols )
    {
      size_t i, j;
    
      for (i = 0; i < rows; i++)
      {
        for (j = 0; j < cols; j++)
        {
          a[i * rows + j] = some_value();
        }
      }
    }
    
    int main( void )
    {
      int arr[10][20];
    
      foo( &arr[0][0], 10, 20 );
      ...
      return 0;
    }
    

    This will work for arrays allocated on the stack:

    T a[M][N];
    

    and for dynamically allocated arrays of the form:

    T (*ap)[N] = malloc( M * sizeof *ap );
    

    since both will have contiguously allocated rows. This will not work (or at least, not be guaranteed to work) for dynamically allocated arrays of the form:

    T **ap = malloc( M * sizeof *ap );
    if (ap)
    {
      size_t i;
      for (i = 0; i < M; i++)
      {
        ap[i] = malloc( N * sizeof *ap[i] );
      }
    }
    

    since it's not guaranteed that all the rows will be allocated contiguously to each other.

提交回复
热议问题