简体   繁体   English

在全局 Scope 中声明二维向量会导致分段错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM