Variable Sized Arrays - hackerrank question

I am doing questions on hackerrank, and got to one i couldnt figure out so i had to look at the answer, but that has not helped much as some of the code looks unfamiliar to me, and I have not done a lot of work with 2d arrays.

What I am mostly wondering about is the line arr[i] = new int[k], so does this line create a 2d array? Or is arr[i] like a pointer to the new array that is created, and that is why arr is a pointer to a pointer?

The whole question can be seen here if wanted https://www.hackerrank.com/challenges/variable-sized-arrays/problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
      int n, q;
    cin >> n >> q;

    int **arr = new int*[n];
    for ( int i = 0, k ; i < n ; ++ i )
    {
        cin >> k;
        
        arr[i] = new int[k];
        
        for ( int j = 0 ; j < k ; ++ j )
        {
            cin >> arr[i][j];
        }
    }
    
    for ( int i = 0, a, b ; i < q ; ++ i )
    {
        cin >> a >> b;
        
        cout << arr[a][b] << endl;
    }
    
	return 0;
}
Last edited on
A "2D" array can be thought of as an array of arrays.
The first layer is a pointer to the outer array, which is an array of pointers (so it's a "pointer to pointers").
The second layer is each pointer within the outer array, where each inner pointer points to an array of ints.

1
2
3
4
5
6
[**] // n = 4
  🠗
 [*], 🠒 [1, 2, 3]                  // k = 3
 [*], 🠒 [2, 4, 6, 8, 5]            // k = 5
 [*], 🠒 [100, 1, -42, 17, 3, 3, 3] // k = 7
 [*]  🠒 [200, 100]                 // k = 2 


When 'k' varies, this is also known as a jagged array.
https://en.wikipedia.org/wiki/Jagged_array
Last edited on
ok, I think i am understanding it a bit more, the drawing out of the arrays defo helped.

Because arr is created as a pointer to an array of pointers, when I do the arr[n] that just refers to the n location in the array of pointers? just like a normal pointer to an array would? And the arr[n][n] just does the same. Using the [] basically just double derefences then?

yes.
Topic archived. No new replies allowed.