How can I pass a dynamic multidimensional array to a function?

后端 未结 9 2270
再見小時候
再見小時候 2020-12-19 05:48

How can I pass a multidimensional array to a function in C/C++ ?

The dimensions of array are not known at compile time

相关标签:
9条回答
  • 2020-12-19 06:04

    Use a vector of vectors, you can pass a vector.

    0 讨论(0)
  • 2020-12-19 06:04

    A simple method is to flatten the array and iterate using dimensions.

    #include <stdio.h>
    
    void print_array(int *arr,int row,int col)
    {
         int i,j;
         for(i=0;i<row;i++){           
             for(j=0;j<col;j++){
                 printf("%d ",*(arr+i*col+j));
             }
             printf("\n");
         }
    }
    
    int main()
    {
    int a[2][3] = {{1,0,2},{-1,3,1}};
    int b[4] = {1,2,3,34};
    print_array(a,2,3);
    return 0;
    }
    

    This technique works but flattening array might prevent compiler optimizations which in turn might result in slow execution.

    0 讨论(0)
  • 2020-12-19 06:06

    A pointer to the start of the array along with the dimensions - then do the array arithmetic in the function is the most common solution.

    Or use boost

    0 讨论(0)
  • 2020-12-19 06:10

    Section 3.4 on this page addresses your question:

    http://www.programmersheaven.com/2/Pointers-and-Arrays-page-2

    Of course variable-length arrays were not present in C until C99 and as far as I know they are not present in C++. Also, MSVC does not implement/support C99.

    0 讨论(0)
  • 2020-12-19 06:12

    Passing the array is easy, the hard part is accessing the array inside your function. As noted by some of the other answers, you can declare the parameter to the function as a pointer and also pass the number of elements for each dim of the array.

    #define xsize 20
    #define ysize 30
    int array[xsize][ysize];
    void fun(int* arr, int x, int y)
    {
     // to access element 5,20
     int x = arr[y*5+20];
    }
    
    fun(array, xsize, ysize);
    

    Of course, I've left out the whole business of allocating the array (since it isn't known what its size will be, you can't really use #defines (and some say they're bad anyhow)

    0 讨论(0)
  • 2020-12-19 06:12

    You could pass a pointer and sizes, or use a std::vector. But the "real" solution is with a template:

    template <size_t N, size_t M>
    void foo(int (&pArray)[N][M]);
    

    This function template accepts a N by M array of ints, by reference. Note this is a function template, not a function, so you do get a different instantiated function per array type.

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