Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding a dynamically allocated array

I have allocated an array as follows.

#include <iostream>

int main() {
    const int first_dim = 3;
    const int second_dim = 2;

    // Allocate array and populate with dummy data
    int** myArray = new int*[first_dim];
    for (int i = 0; i < first_dim; i++) {
        myArray[i] = new int[second_dim];
        for (int j = 0; j < second_dim; j++) {
            myArray[i][j] = i*second_dim + j;
            std::cout << "[i = " << i << ", j = " << j << "] Value: " << myArray[i][j] << "\n";
        }
    }

    // De-allocate array
    for (int i = 0; i < first_dim; i++)
        delete[] myArray[i];
    delete[] myArray;
}

Let's say I want to add a 4th element to the first dimension, i.e. myArray[3]. Is this possible?

I've heard that Vectors are so much more efficient for this purpose, but I hardly know what they are and I've never used them before.

like image 847
Pieter Avatar asked Mar 23 '26 07:03

Pieter


1 Answers

Yes, but in a very painful way. What you have to do is allocate new memory which now has your new desired dimensions, in this case 4 and 2, then copy all the contents of your matrix to your new matrix, and then free the memory of the previous matrix... that's painful. Now let's see how the same is done with vectors:

#include <vector>
using std::vector;

int main()
{
   vector< vector <int> > matrix;
   matrix.resize(3);
   for(int i = 0; i < 3; ++i)
      matrix[i].resize(2);

   matrix[0][1] = 4;
   //...

   //now you want to make the first dimension 4? Piece of cake

   matrix.resize(4);
   matrix[3].resize(2);
}

HTH

edit: some comments on your original code:

  • In C++ ALL_CAP_NAMES usually refer to macros (something you #define). Avoid using them in other contexts
  • why do you declare FIRSTDIM and SECONDDIM static? That is absolutely unnecessary. If a local variable is static it means informally that it will be the same variable next time you call the function with kept value. Since you technically can't call main a second sime this is useless. Even if you could do that it would still be useless.
  • you should wrire delete [] array[i]; and delete [] array; so the compiler knows that the int* and int** you're trying to delete actually point to an array, not just an int or int* respectively.
like image 73
Armen Tsirunyan Avatar answered Mar 25 '26 21:03

Armen Tsirunyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!