'Why I got runtime error while I am using local N instead of global N?
In this code when I use N is globally it works but using the same value as a local variable shows a runtime error. But I can not fix the problem. Actually, why should I use this N globally?
void solve()
{
long long n;
cin >> n;
long long N=210; /// But when I use this locally it shows runtime error
long a[N];
long long dp[N][N];
for(int i=1; i<=n; i++){
cin >> a[i];
}
sort(a, a+n+1);
dp[0][0]=0;
for(int i=1; i<=n; i++)
{
dp[i][0]=1e9;
for(ll j=1; j<=2*n; j++){
dp[i][j]=min(dp[i][j-1], dp[i-1][j-1]+abs(a[i]-j));
}
}
long long ans=dp[n][2*n];
cout << ans << '\n';
}
Solution 1:[1]
long long N; /// But when I use this locally it shows runtime error long a[N];
There are two problems with this:
Nis uninitialised. The behaviour of the program is undefined since you read the value of an uninitialised object.Nis not compile time constant. It cannot be used as the size of an array variable. The program is ill-formed.
If N was global, then it would be zero-initialised, so the first problem would be resolved. However, that would introduce another problem that the size would be zero which isn't allowed for array variables. The non-constant problem also remains.
To properly solve 1. initialise the variable before attempting to use its value.
To properly solve 2. either use compile time constant size or create a dynamic array. The simplest way to do the latter is to use std::vector. There's no need to use a global variable:
std::size_t N;
std::cin >> N;
std::vector<long> a(N);
long a[N]; // ... for(int i=1; i<=n; i++){ cin >> a[i]; } sort(a, a+n+1);
There's a potential problem here. If N is less than or equal to n, then this will overflow a and the behaviour of the program will be undefined.
Furthermore, you never initialised a[0] so when std::sort reads it, the behaviour of the program will be undefined.
I recommend using range-based loops to avoid overflows:
for(int& element : a) {
std::cin >> element;
}
std::ranges::sort(a);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user17732522 |
