Pass By Reference Multidimensional Array With Unknown Size

前端 未结 5 542
没有蜡笔的小新
没有蜡笔的小新 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

    This is a sort of comment to the good answer of @John Bode

    This will not work (or at least, not be guaranteed to work) for dynamically allocated arrays of the form:

    But this variant will:

    T **ap = malloc( M * sizeof *ap );
    if (ap) return NULL;     ---> some error atention
    if (ap)
    {
      ap[0] = malloc( M * N * sizeof *ap[i] );
      if (ap[0]) { free(ap); return NULL;}     ---> some error atention
      size_t i;
      for (i = 1; i < M; i++)
      {
        ap[i] = ap[0] + i * N;
      }
    }
    

    After use :

    free(ap[0]);
    free(ap);
    

    for T being int you call foo exactly als for the array int ap[M][N];

      foo( &ap[0][0], M, N);
    

    since you guaranteed that all the rows are allocated contiguously to each other. This allocation is a litter more efficient.

提交回复
热议问题