-1

The value of K varies from array to array. How to do this?

This is what I have to achieve. Its the hackerrank variable sizedarray question. https://s3.amazonaws.com/hr-challenge-images/14507/1476906485-2c93045320-variable-length-arrays.png

I've read the solutions but am unable to understand it. Please explain this line of code : int** seq=new int* [n];

Following is the complete code from which the snippet has been taken.

int main()
{
    int n,q;
    cin>>n>>q;
    int** seq=new int* [n];
    for(int i=0;i<n;i++)
    {  
      int a;
      cin>>a;
      int* b=new int [a];
      for(int j=0;j<a;j++)
        {
          int e;
          cin>>e;
          b[j]=e;
        }
       *(seq+i)=b;
   }

  for(int i=0;i<q;i++)
  {

      int r,s;
      cin>>r>>s;
      cout<<seq[r][s]<<endl;

  }
}

I've also read something about using vector to create variable sized array. I don't understand. please explain.

1 Answers1

0

if you write int *p, this means you are defining a pointer which will store the address of an integer.

Similarly, int **p means a pointer to an integer pointer.

Now, let's suppose you create a 1D array like this:

int *a = new int[10];

here the pointer "a" points to the address of the first element, an integer, of the array "new" just created.

To access the individual elements you can use a[i] or simply *(a+i).

now, coming to your question.

int **seq = new int*[n];

the "new" here would create an array of "pointers". So to point to the first element, which is a pointer here, you need to use a pointer to a pointer. That is why **seq.

  • Thanks a ton! However I have a doubt, if I were to write int *seq=new int*[n]; what does this imply?Does this mean anything? or is it just a syntax error? – srishti_pathak Jul 10 '17 at 18:17
  • It will give an error. new int*[n] would, as explained earlier, would return a pointer to a pointer. So if you write int *seq, here seq can store the address of an integer and NOT a pointer to an integer. So this will definitely show error. – Aditya Kumar Jul 13 '17 at 18:42