简体   繁体   中英

error in passing the 2D array to a function in c++

unusual error in function solve when I pass the dp array to the function.

int n,k;
int solve(int n, int k, int dp[n+1][k+1]) 
{ 
  // some code
} 
int main(){
  int t; cin>>t;
  while(t--){
     cin>>n;
     cin>>k;
     int dp[n+1][k+1];
    memset(dp, -1,sizeof(dp));
    cout<<solve(n,k,dp)<<endl;
  }
return 0;
}

why this error: use of parameter outside function body before '+' token int solve(int n, int k, int dp[n+1][k+1]) I am not able to understand why is this error

In C++ array sizes must be compile time constants .

This is not legal C++

int dp[n+1][k+1];

because n and k are variables not constants.

And this is not legal C++

int solve(int n, int k, int dp[n+1][k+1]) 

for exactly the same reason.

In C++, the array's size can't be changed dynamically. Granted you are reading in the sizes, this will cause issues. You can hard code the value of n,k for testing purposes

int dp[10][10];
int solve(int n, int k, int dp[10][10])

or attempt using a vector instead.

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