简体   繁体   English

C++ 向量和数组

[英]C++ vector and array

I was trying to solve a HackerRank question named "Array Manipulation" The link of the problem .我试图解决一个名为“Array Manipulation” HackerRank 问题 问题的链接 I wrote this code below.我在下面写了这段代码。 It works fine.它工作正常。 However, when I use an array instead of vector I got segmentation fault at case 7-13.但是,当我使用数组而不是向量时,我在案例 7-13 中遇到了分段错误。 Why did it happen?为什么会这样?

long arrayManipulation(int n, vector<vector<int>> queries) {
    vector<long> arr(n);
    long sum=0, max=LONG_MIN;
    for(int i=0;i<n;i++){
        arr[i] = 0;
    }
    for(int i=0;i<queries.size();i++){
        arr[queries[i][0]-1] += queries[i][2];
        if(queries[i][1]<n) arr[queries[i][1]] -= queries[i][2];
    }
    for(int i=0;i<n;i++){
        sum += arr[i];
        if(sum>max) max=sum;
    }
    return max; }
long arrayManipulation(int n, vector<vector<int>> queries) {
    long arr[n];
    long sum=0, max=LONG_MIN;
    for(int i=0;i<n;i++){
        arr[i]=0;
    }
    for(int i=0;i<queries.size();i++){
        arr[queries[i][0]-1]+=queries[i][2];
        if(queries[i][1]<n) arr[queries[i][1]]-=queries[i][2];
    }
    for(int i=0;i<n;i++){
        sum+=arr[i];
        if(sum>max) max=sum;
    }
    return max;
}

Variable length arrays have a limit of available stack limit, if it surpasses the limit SegV (by stack overflow) can occur.可变长度数组有一个可用堆栈限制,如果超过限制,SegV(堆栈溢出)就会发生。

The same can happen for fixed length array if size is large enough.如果大小足够大,固定长度数组也会发生同样的情况。

Try with this to see the issue:试试看这个问题:

long arr[10000000];  // should fail for same reason in HackerRank

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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