lundi 25 juin 2018

Increasing the size of an array during runtime

I want to dynamically allocate an array in a for loop using pointers. As the for loop proceeds, the size of the array should increase by one and a new element should be added then. The usual method involves using the new operator, but this always allocated a fixed memory at the time of declaration. Is there any way to do so?

I tried to do so using the following code (simplified for explaing the problem):

sameCombsCount = 0;
int **matchedIndicesArray;    
for(int i = 0; i<1000; i++) //loop condition a variable
{
  sameCombsCount++;

  matchedIndicesArray = new int*[sameCombsCount]; // ??
  // Now add an element in the new block created...
}

The thing is, I do not know the size of the for loop during execution time. It can vary depending upon execution conditions and inputs given. I don't think this is the correct way to do so. Can someone suggest a way to do so?

Aucun commentaire:

Enregistrer un commentaire