Home > database >  Multidimensional array with variable length sub arrays
Multidimensional array with variable length sub arrays

Time:12-15

I am trying to make a 2D array with each sub array of variable length using the following code. When I try to access the values in the array sometimes it gives the correct value for one query but mostly outputs garbage values. I can't seem to understand what I am doing wrong.

#include <iostream>
using namespace std;


int main() {
    
    int size, queries;
    
    cin >> size >> queries;
    
    int **p = new int *[size];
    
    int sub_size;
    
    for (int i =0; i< size; i  ) {
        cin >> sub_size;
        int *sub_arr = new int[sub_size]
        
        for (int j=0; j<sub_size; j  ) {
            cin >> sub_arr[j];
        }
        
        //p[i] = sub_arr;
        *p = sub_arr;
        p  ;
        
    }
    
    int r, c;
    
    
    for (int i=0; i<queries; i  ) {
        cin >> r >> c;
        cout << p[r][c] << endl;
    }
    
    delete []p;
     
    return 0;
}

I have made changes to the code now sub array is also declared using new[]

CodePudding user response:

I fixed the code. The problem was that I was incrementing p using p so p was no longer pointing to the start of the pointer array. So I used a new pointer called temp to manipulate the 2D array:

int main() {
    
    int size, queries;
    
    cin >> size >> queries;
    
    int **p = new int *[size];
    int **temp = p; //temp also points to the same array of pointers
    
    int sub_size;
    
    for (int i =0; i< size; i  ) {
        cin >> sub_size;
        int *sub_arr = new int[sub_size];
        
        for (int j=0; j<sub_size; j  ) {
            cin >> sub_arr[j];
        }
        
        //p[i] = sub_arr;
        *temp = sub_arr;
        temp  ;
        
    }
    
    int r, c;
    
    
    for (int i=0; i<queries; i  ) {
        cin >> r >> c;
        cout << p[r][c] << endl;
    }
    
    delete []p;
     
    return 0;
}
  • Related