educative.io

I don't understand how the dynamic arrays are different

Because here when you resize

int main() {

// Initialize variable size

int size = 5;

// Create Array

int * Arr = new int[size];

// Fill elements of an array

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

Arr[i] = i;

}

// Call printArray function

printArray(Arr, size);

// Create new array

int * ResizeArray = new int[size + 2];

// Copy elements in new arary

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

ResizeArray[i] = Arr[i];

}

// Delete old array

delete[] Arr;

// Pointer Array will point to ResizeArray

Arr = ResizeArray;

// Store new values

Arr[size] = 90;

Arr[size + 1] = 100;

// Call printArray function

printArray(Arr, size + 2);

}

You are really just making another array and changing the pointer of the first array.

Blockquote


Course: Learn C++: The Complete Course for Beginners - Learn Interactively
Lesson: Dynamic Arrays - Learn C++: The Complete Course for Beginners

Hi @Hao,

Thank You for reaching out to the Educative team.

Yes, you are correct in noting that the “resizing” is achieved by creating a new array. We can grow and shrink the dynamic array during the program execution.

When we want to resize a dynamic array the steps we follow are

  1. Create/Allocate a new array with size greater than the previous array
    int * ResizeArray = new int[size + 2];
  2. Copy the elements from the old array to the new array
    ResizeArray[i] = Arr[i];
  3. (Delete) Free the memory occupied by the old array to prevent memory leaks
    delete[] Arr;
    In the above we have just deleted the memory not the variable Arr
  4. Redirect the pointer to the new array
    Arr = ResizeArray;

The size of a static array is fixed and cannot be changed during runtime, while in dynamic arrays the size can be changed during program execution which is achieved by following the above steps.

I hope it helps. Happy Learning :blush: