为什么在使用本地 N 而不是全局 N 时出现运行时错误?
在此代码中,当我全局使用 N 时,它可以工作,但使用与局部变量相同的值会显示运行时错误。但我无法解决这个问题。其实我为什么要全局使用这个N呢?
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';
}
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';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这有两个问题:
N
未初始化。由于您读取了未初始化对象的值,因此程序的行为是未定义的。N
不是编译时常数。它不能用作数组变量的大小。该程序格式不正确。如果
N
是全局的,那么它将被零初始化,因此第一个问题将得到解决。但是,这会引入另一个问题,即大小为零,这对于数组变量来说是不允许的。非恒定问题仍然存在。正确解决方法 1. 在尝试使用变量值之前初始化该变量。
要正确解决 2. 问题,请使用编译时常量大小或创建动态数组。执行后者的最简单方法是使用 std::vector。无需使用全局变量:
这里有一个潜在的问题。如果
N
小于或等于n
,那么这将溢出a
并且程序的行为将是未定义的。此外,您从未初始化
a[0]
,因此当std::sort
读取它时,程序的行为将是未定义的。我建议使用基于范围的循环来避免溢出:
There are two problems with this:
N
is uninitialised. The behaviour of the program is undefined since you read the value of an uninitialised object.N
is 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:There's a potential problem here. If
N
is less than or equal ton
, then this will overflowa
and the behaviour of the program will be undefined.Furthermore, you never initialised
a[0]
so whenstd::sort
reads it, the behaviour of the program will be undefined.I recommend using range-based loops to avoid overflows: