gpt4 book ai didi

c++ - 辛>>一>>乙; C++ 错误

转载 作者:行者123 更新时间:2023-11-27 23:35:43 25 4
gpt4 key购买 nike

奇怪的是我找不到任何问题,但它只是崩溃了。在代码第 22 行,错误发生的地方。当输入一对数字的第二行时,程序崩溃。

#include <iostream>
#include <queue>
using namespace std;

int main(){
int t;
cin>>t;
int n, e, s, u, v;
int* martix = nullptr, *mask = nullptr;
for(int i = 0; i<t; i++){
cin>>n>>e>>s;
martix = new int[n*n];
mask = new int[n];
for(int i = 0; i<n*n; i++){
mask[i] = 0;
for(int j = 0; j<n; j++){
martix[i*n+j] = 0;
}
}

while (e--){
cin>>u>>v;//when inputing this two int variable in second time, program crashes
martix[u*n+v] = 1;
martix[v*n+u] = 1;
}

cout<<s<<' ';
mask[s] = 1;
queue<int> q;
q.push(s);
while(!q.empty()){
s = q.front();
q.pop();
for(int i=0; i<n; i++){
if(martix[s*n+i]!=0&&mask[i]!=1){
cout<<i<<' ';
q.push(i);
mask[i] = 1;
}
}
}
cout<<endl;
delete [] mask;
delete [] martix;
}
return 0;
}

测试用例:

1
6 7 0
0 3
0 4
1 4
1 5
2 3
2 4
3 5

预期输出:

0 3 4 2 5 1

enter image description here

最佳答案

i 有可能跑到 n * n - 1j 跑到 n - 1

此时(及之前),用作数组索引的表达式 i * n + j 超出了数组边界。这是未定义的行为,并且正在(有帮助地)表现为崩溃。

您的意思是只运行 i 直到 n,而不是正方形吗?

请注意,如果您在裸数组上使用 std::vector.at 方法而不是 [],则 C++运行时会抛出一个异常,这对诊断和修复来说是微不足道的。

关于c++ - 辛>>一>>乙; C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59356089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com