简体   繁体   中英

C++: Variable Size 2D array as an argument to a function

I need the simplest way to solve this issue: when i tried to compile the code below, it says you cant use nR outside the body of the function, passing double pointer in declaration of the function does not work, because it did not allow me to cast, :

A(int nT, int nR, int arr[][nR]){
for(int i = 0; i< nT; i++){
    for(int j = 0; j< nR; j++){
        cout<< arr[i][j] << endl;}
    }
}

int main(){
int requests[2][3] = { { 1, 2, 3} , { 4, 32, 6 } };
A(2,3, requests );
return 0;
}

You can do it if you make your function a template:

template<std::size_t N, std::size_t M>
A(int (&arr)[N][M]){
  for(int i = 0; i< N; i++){
    for(int j = 0; j < M; j++){
        cout<< arr[i][j] << endl;
    }
  }
}

And then in main:

int main(){
  int requests[2][3] = { { 1, 2, 3} , { 4, 32, 6 } };
  A(requests);
  return 0;
}

C++ (and C) arrays are not resizeable and do not contain size information.

To do this you should use std::vector

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM