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?
int n, q;
cin >> n >> q;
int **arr = newint*[n];
for ( int i = 0, k ; i < n ; ++ i )
{
cin >> k;
arr[i] = newint[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;
}
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.
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?