Pass By Reference Multidimensional Array With Unknown Size

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

    Simply put, you can't. In C, you can't pass by reference, since C has no references. In C++, you can't pass arrays with unknown size, since C++ doesn't support variable-lenght arrays.

    Alternative solutions: in C99, pass a pointer to the variable-length array; in C++, pass a reference to std::vector>.

    Demonstration for C99:

    #include 
    
    void foo(int n, int k, int (*arr)[n][k])
    {
        int i, j;
        for (i = 0; i < n; i++) {
            for (j = 0; j < k; j++) {
                printf("%3d ", (*arr)[i][j]);
            }
            printf("\n");
        }
    }
    
    int main(int argc, char *argv[])
    {
        int a = strtol(argv[1], NULL, 10);
        int b = strtol(argv[2], NULL, 10);
    
        int arr[a][b];
        int i, j;
        for (i = 0; i < a; i++) {
            for (j = 0; j < b; j++) {
                arr[i][j] = i * j;
            }
        }
    
        foo(a, b, &arr);
    
        return 0;
    }
    

    Demonstration for C++03:

    #include 
    #include 
    #include 
    #include 
    
    void foo(std::vector < std::vector < int > > &vec)
    {
        for (std::vector < std::vector < int > >::iterator i = vec.begin(); i != vec.end(); i++) {
            for (std::vector::iterator j = i->begin(); j != i->end(); j++) {
                std::cout << *j << " ";
            }
            std::cout << std::endl;
        }
    }
    
    int main(int argc, char *argv[])
    {
        int i = strtol(argv[1], NULL, 10);
        int j = strtol(argv[2], NULL, 10);
    
        srand(time(NULL));
    
        std::vector < std::vector < int > > vec;
        vec.resize(i);
        for (std::vector < std::vector < int > >::iterator it = vec.begin(); it != vec.end(); it++) {
            it->resize(j);
            for (std::vector::iterator jt = it->begin(); jt != it->end(); jt++) {
                *jt = random() % 10;
            }
        }
    
        foo(vec);
    
        return 0;
    }
    

提交回复
热议问题