【问题标题】:getting segmented fault error in hackerrank problem- Variable Length Array [duplicate]在hackerrank问题中出现分段错误错误-可变长度数组[重复]
【发布时间】:2021-07-04 06:22:34
【问题描述】:

https://www.hackerrank.com/challenges/variable-sized-arrays/problem

这是问题陈述。 我尝试了以下代码

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int n,q;
    cin>>n>>q;
    int n1;
    int A[n][1000000];
   
for(int i =0; i<n; i++)   
{ cin>>n1;
     
    for(int j=0; j<n1; j++){
        int c;
        cin>>c;
        A[i][j] = c;
    }
}

int a,b;
for(int i=0;i<q; i++){
cin>>a>>b;
    
    cout<<A[a][b]<<"\n";
}
    return 0;
}

此代码通过了示例测试用例和其他自定义输入(我尝试了少量输入值)。但它不适用于 n 和 q 的值(如问题中所述)很大的测试用例。它给出了“分段故障”错误。有人可以解释为什么我会收到这个错误。

【问题讨论】:

  • 你得到一个(名词预兆)堆栈溢出。这个数组太大了,栈内存放不下,所以程序崩溃了。
  • VLA's are not part of the C++ standard 你发现了不应该使用它们的原因之一。您可以改用std::vector
  • 顺便说一句,在“输入格式”之前的最后一行,问题本身将您链接到创建可变长度数组的正确方法。它叫std::vector
  • @Yksisarvinen 谢谢

标签: c++ variable-length-array


【解决方案1】:

在这里int A[n][1000000]; 你分配了n * 1000000 数量的元素。这是一个巨大的数字。如果我们认为 int 是 32 位(或 4 个字节),那么您谈论的 n * 4000000 字节的数据很可能会在兆字节范围内,因此您的错误。这很容易被堆栈分配太多,而且效率很低。
考虑改用std::vector&lt;&gt;

【讨论】:

  • 谢谢,帮了大忙。
猜你喜欢
  • 2012-05-04
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 2020-09-01
  • 1970-01-01
相关资源
最近更新 更多