top of page

Array in c++

An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar type of elements as in the data type must be the same for all elements. They can be used to store collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can store derived data types such as the structures, pointers etc. Given below is the picturesque representation of an array.


// Array declaration by specifying size

int arr1[10];


// With recent C/C++ versions, we can also

// declare an array of user specified size

int n = 10;

int arr2[n];


// Array declaration by initializing elements

int arr[] = { 10, 20, 30, 40 };


// Array declaration by specifying size and initializing

// elements

int arr[6] = { 10, 20, 30, 40 };


Example array.cpp:

#include <iostream>

using namespace std;

int main()

{

int arr[5];

arr[0] = 5;

arr[2] = -10;

// this is same as arr[1] = 2

arr[3 / 2] = 2;

arr[3] = arr[0];

cout << arr[0] << " " << arr[1] << " " << arr[2] << " " << arr[3];

return 0;

}

Advantages of an Array in C/C++:

  1. Random access of elements using array index.

  2. Use of less line of code as it creates a single array of multiple elements.

  3. Easy access to all the elements.

  4. Traversal through the array becomes easy using a single loop.

  5. Sorting becomes easy as it can be accomplished by writing less line of code.

Disadvantages of an Array in C/C++:

  1. Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.

  2. Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.


Array vs Pointers

Arrays and pointer are two different things (we can check by applying sizeof). The confusion happens because array name indicates the address of first element and arrays are always passed as pointers (even if we use square bracket).

コメント


bottom of page