I'm working through the C++ Hackerrank modules, and I've come across a problem asking to output certain values in a two-dimensional array. Here is the problem:
Consider an n-element array,
a
, where each indexi
in the array contains a reference to an array ofk
integers (where the value ofk
varies from array to array)... Givena
, you must answerq
queries. Each query is in the formati j
, wherei
denotes an index in array a andj
denotes an index in the array located ata[i]
. For each query, find and print the value of elementj
in the array at locationa[i]
on a new line.
I don't want to make this entire question a quote, so here is the link: Variable Sized Arrays. Basically, there is the first input line with the above-mentioned n
and q
. Then there are n
lines of integers following, with the first integer in each line of input being k
, and this is the number of integers following k
itself in the input line. After these n
lines is one line with two integers i
and j
, denoting the array index and element index respectively.
So, the solution is then to create a two-dimensional array that can be filled in with n
sub-arrays. Here was my code originally:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, q;
cin >> n >> q;
int a[n];
for(int i=0; i<n; i++){
int k;
cin >> k;
int subA[k];
for(int j=0; j<k; j++)
cin >> subA[j];
arr[i] = subA[k];
}
for (int x=0; x<q; x++){
int i, j;
cin >> i>> j;
cout << a[i][j] << endl;
}
return 0;
}
The error said
invalid types 'int[int]' for array subscript
cout << a[i][j] << endl;
and I realized that it was probably because an array isn't an integer type (right?). So then after googling, I came across this question, which just nonchalantly skips over the fact that one seems to need pointers to create two-dimensional arrays.
So, when a two-dimensional array is created, does it require the use of pointers? If so, would I be right in stating that pointers are required because they aren't really a type like int
or char
, but just hold an address whose type doesn't have to be known?
P.S. I understand that the first link I provided provides in itself a link to something about vectors. It didn't give any examples and I have no idea what they are, and googling and Stackoverflow-ing hasn't really helped (especially the i/o part), so I just used something familiar to me, and it seems, through this process of googling and Stackoverflow-ing, that vectors are not needed for a solution such as the high-level one I posed above.