Search code examples
c++arrayspointersdynamic-arraysvariable-length-array

I need to create an n-element array a where each index i has a reference to another array of K integers


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.


Solution

  • 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.