0

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

Ann
  • 53
  • 8
  • 1
    Because it's not valid C++. –  Jul 14 '19 at 20:05
  • 1
    Let me direct you to `std::vector`, which can be used in the manner the code is trying to use a C-style array. – Eljay Jul 14 '19 at 20:06
  • This [answer](https://stackoverflow.com/questions/57023066/count-of-equal-adjacent-elements-in-2d-array/57025549#57025549) here will be helpful on learning how to properly pass an array to a function – parth_07 Jul 14 '19 at 23:30

2 Answers2

2

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.

john
  • 85,011
  • 4
  • 57
  • 81
0

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.