Wednesday, January 31, 2024

Array

What is Array?


An array is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures and often used to implement other data structures. Each item in array is indexed starting with 0.




Representation Of Array
The representation of an array can be defined by its declaration. A declaration means allocating memory for an array of a given size.

There are 2 types of Array:
  1. Static Array
  2. Dynamic Array

1. Static Array:
Static Arrays are arrays that are declared before runtime and are assigned values while writing the code. It allocates memory at compile-time whose size is fixed. We cannot alter the static array.
Example: int arr[] = { 1, 3, 4 }; // static integer array  

Advantages of Static Array

  • It has efficient execution time.
  • The lifetime of static allocation is the entire run time of the program.

Disadvantages of Static Array

  • In case more static data space is declared than needed, there is waste of space.
  • In case less static space is declared than needed, then it becomes impossible to expand this fixed size during run time.
Dynamic Array

If we want an array to be sized based on input from the user. In such a case, dynamic arrays allow us to specify the size of an array at run-time.
Example: int* arr = new int[3]; // dynamic integer array  

The dynamic array is a variable size list data structure. It grows automatically when we try to insert an element if there is no more space left for the new element. It allows us to add and remove elements. It allocates memory at run time using the heap. It can change its size during run time.


No comments:

Post a Comment