Static vs Dynamic Arrays

  • This refers to the size of the array being static vs dynamic.

  • Once an array is created, its size cannot be modified, because the memory for this array will be created inside of the stack.

  • The size of this array was decided at compile time and must be a constant value, though memory will be allocated during runtime only (cannot be allocated at compile time).

void main() {
  int A[5];
}
  • But in C++, we can create an array of any size at runtime, and it will be created inside of the stack only.
  • We can do something like this:
void main() {
  int n;
  cin >> n;
  int B[n];
}

Dynamic Arrays

  • Here whatever we input on the keyboard, we can create an array of that size. So, the size of the array is decided at runtime.

  • We can make a dynamic array, by creating an array inside the heap, whose size and type is decided at runtime.

  • For accessing anything inside the heap, we must have a pointer.

void main() {
  int *p;
  p = new int[5];
}
void main() {
  int *p;
  p = (int *)malloc(5 * sizeof(int));
}

  • You only get memory from heap whenever you say "new". Otherwise all the variables will be in the stack only.

  • "malloc" will just allocate a raw block of memory. To use it as an integer, we must type cast it as an integer pointer.

  • After you have allocated memory, and after some time during the execution of the program, if that memory is not required, you must delete it. Otherwise it causes a memory leak problem.

  • In C++, we must say delete[] p;.

  • In C, we must say free(p);.

  • To access an array in the heap, it's the same as a stack allocated array.

  • It is only possible to resize an array if it is heap allocated.