Variable Sized Arrays

  • + 0 comments

    it seems that there's a potential issue that could lead to a segmentation fault. This can occur if the values of i and j in your queries go out of bounds of the array a.

    You might want to include some checks to ensure that i and j are within the valid range before accessing a[i][j]. Here's an updated version of your code that includes these checks:

    include

    using namespace std;

    int main() { long long i, j, x, n, q, k, a[10000][10000];

    cin >> n >> q; // read the number of lines and queries
    
    // save the arrays as a matrix
    for (i = 0; i < n; i++) {
        cin >> k; // read the number of columns
        for (j = 0; j < k; j++) {
            cin >> a[i][j]; // read the value
        }
    }
    
    // solve the queries
    for (x = 0; x < q; x++) {
        cin >> i >> j; // read the position of the wanted value
    
        if (i >= 0 && i < n && j >= 0 && j < k) {
            cout << a[i][j] << endl; // write the found value
        } else {
            cout << "Invalid query!" << endl;
        }
    }
    
    return 0;
    

    } This code includes a check to ensure that i is within the range of [0, n) and j is within the range of [0, k) before accessing a[i][j]. This should help prevent potential segmentation faults caused by accessing elements outside the array bounds.