Skip to content

Instantly share code, notes, and snippets.

@hckim16
Created February 24, 2018 02:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hckim16/b37987d5b7ff66501cb9dd508ae1bf37 to your computer and use it in GitHub Desktop.
Save hckim16/b37987d5b7ff66501cb9dd508ae1bf37 to your computer and use it in GitHub Desktop.
Hackerrank C++ Variable Sized Arrays challenge
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int q;
cin >> n >> q;
vector<int> a[n];
for(int i = 0; i < n; i++){
int m;
cin >> m;
int o;
for(int j = 0; j < m; j++){
cin >> o;
a[i].push_back(o);
}
}
int r, s;
for(int k = 1; k <= q; k++){
cin >> r >> s;
cout << a[r][s] << endl;
}
return 0;
}
@budagabrielchristian
Copy link

`
#include
#include

using namespace std;

int main() {
int numOfArrays, numOfQueries;

cin >> numOfArrays >> numOfQueries;

int arrayIndexes[100000];
int elementIndexes[100000];
int board[numOfArrays][300000];

for(int i = 0; i < numOfArrays; i++){
    int limit;
    cin >> limit;
    for(int j = 0; j < limit; j++){
        cin >> board[i][j];
    }
}

for(int l = 0; l < numOfQueries; l++){
    int arrayIn, elementIn;
    cin >> arrayIn >> elementIn;
    arrayIndexes[l] = arrayIn;
    elementIndexes[l] = elementIn;
}

for(int j = 0; j < numOfQueries; j++){
    int currentArr = arrayIndexes[j], currentElement = elementIndexes[j];
    cout << board[currentArr][currentElement] << endl;
}
return 0;

}
`
I get segmentation fault myself, does anyone know what exactly is wrong with my code?

@dabir-supremacy
Copy link

dabir-supremacy commented Dec 13, 2022

You are getting a segmentation fault.
Segmentation fault occurs when you are trying to access memory which you dont own, consequently to prevent memory from getting corrupted and unusable C++ has a built-in mechanism to prevent this, which raises the SegFault/Segmentation Fault/Core dump.

to prevent this from occurring try breaking you problem into parts and converting your code in different 'functions'.

this may seem primitive but if anyone has an expert solution, im all ears.

EDIT: A vector can also resolve this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment