Array Data Structure
You have only heard that arrays are linear data structures that contain elements of the same data type, but in this blog, you will explore the full world of arrays.
Before diving into arrays, you should know what the main memory looks like.
Arrays
Arrays are linear data structures that store multiple elements sequentially of the same data type. Each element has its index, using which we can refer to it or perform other operations, and its address as well. In a simple variable, we can store a single element at a time but if want to have multiple elements then we need to declare more variables for each element, at that time we prefer an array, using a single variable we are storing multiple elements. Figure 2 illustrates a basic array of size 5 named as A of type int.
Static Array
Array declared inside the Stack of the main memory are known as static arrays, static means they are fixed-sized, and we have to determine the size at the time of declaration.
void main()
{
int A[5]; // it will be inside the stack
return 0;
}
Dynamic Array
Dynamic array is the solution for the limitations of static array, in dynamic array the size is flexible and can be changed dynamically in runtime, allowing elements to be added or removed as required. And we can resize the array as well.
Get Owais Ahmad’s stories in your inbox
Join Medium for free to get updates from this writer.
Using the new operator the array will be created in the heap and with the help of the pointer variable we can point to the array in the heap as shown in the figure the heap part of the main memory is used for dynamic memory allocation.
Heap memory can be accessed directly with the help of a pointer, as in the example at index 0 the value 5 is placed with the help of the pointer variable P, as shown in Figure 3
void main()
{
int *p;
p = new int[5]; // this array will be created in heap
p[0] = 5; // at index 0 we place value 5
return 0;
}After the execution of the program if the heap memory is not required anymore, then it must be deleted, if it is not deleted then it creates a memory leak problem.
Happy Learning!









