Reputation: 105
Passing dimensions of the array to function but still getting an error!
Code (You can directly scroll down to the error it gives and see only those lines in code)
class Solution {
public:
int mod = 1e9 + 7;
int checkRecord(int n) {
int dp[n + 1][2][3];
memset(dp, -1, sizeof(dp));
return helper(0, 1, 2, n + 1, 2, 3, dp);
}
int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {
if(idx == N) return;
if(dp[idx][A][startL] != -1) {
return dp[idx][A][startL];
}
dp[idx][A][startL] = helper(idx + 1, A, 2, N, M, K, dp) % mod;
if(startL > 0) {
dp[idx][A][startL] += helper(idx + 1, A, startL - 1, N, M, K, dp) % mod;
}
return dp[idx][A][startL];
}
};
Error
error: cannot initialize a parameter of type 'int (*)[*][*]' with an lvalue of type 'int [n + 1][2][3]'
return helper(0, 1, 2, n + 1, 2, 3, dp);
^~
note: passing argument to parameter 'dp' here
int helper(int idx, int A, int startL, int N, int M, int K, int dp[][M][K]) {
^
Upvotes: 0
Views: 63
Reputation: 238351
int checkRecord(int n) { int dp[n + 1][2][3];
The size of an array variable must be compile time constant in C++. n + 1
is not compile time constant and as such the program is ill-formed.
If you want to create an array with runtime size, then you must create an array with dynamic storage duration. simplest way to do that is to use std::vector
.
int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {
Same applies to parameters which are also variables. Though there is slight difference since the array parameter will be adjusted to be a pointer to the first element of the array and the outermost dimension of the array i.e. N
is ignored. The type of dp
would be int(*)[M][K]
if M
and K
were compile time constant.
Yeah, but 3d vector is too much to type
vector<vector<..
In order to write long class template instances, you should pace yourself so that you don't get exhausted before the end. In case you are overcome by fatigue, take a short break to recover and continue later. I believe that you can do it.
That said, the inner dimensions of your array seem to be constant, so you don't need to use vectors inside vectors.
if(idx == N) return;
This is an ill-formed return statement in a non-void function.
Upvotes: 2
Reputation: 2152
Seems like you are trying to solve a competitive programming problem. So my answer is going to focus on that. I think others pointed out why it is not valid C++.
In C++, I don't see any easy way to achieve what you want.
In practice, when it comes to competitive programming problems, you may just define a big global array(As problems have fixed input sizes usually. In this case, there would be the max number of N, M, and K) and you don't have to struggle with passing it. Reuse the array for each case, but make sure you initialize it every time. Yeah, this is not a good practice in general but pretty handy for competitive programming.
If you think about 3D vectors are overkill, you may consider this.
Upvotes: 0