[英]Declaring 2D Vector in Global Scope gives segmentation fault
#include <bits/stdc++.h>
using namespace std;
int n;
std::vector<bool> visited(n,false);
std::vector<std::vector<int>> g(n,std::vector<int>(n));
int main() {
cin>>n;
//std::vector<std::vector<int>> g(n,std::vector<int>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin>>g[i][j];
}
}
cout<<g[0][0];
}
2D vector declared inside main function gives no error but when declared in global scope gives SIGSEV error在主 function 内声明的 2D 向量没有错误,但在全局 scope 中声明时会出现 SIGSEV 错误
When visited
and g
get initialized, the value of n
is 0
.当被
visited
并且g
被初始化时, n
的值为0
。 ( n
is declared in global namespace and will be zero-initialized .) So the vector
s are empty and contain no elements. (
n
在全局命名空间中声明并且将被 初始化为零。)所以vector
s 是空的并且不包含任何元素。 Then access to them like g[0][0]
leads to UB.然后像
g[0][0]
一样访问它们会导致 UB。
On the other hand, for the vector g
declared in main()
, n
is set to some value and then used to initialize g
, then g
is initialized as containing n
elements.另一方面,对于
main()
中声明的向量g
,将n
设置为某个值,然后用于初始化g
,然后将g
初始化为包含n
元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.