Array Data Structure

·

2 min read

What is an Array?

An array is just a collection of variables stored at contiguous locations in the memory.

Explanation

It is the simplest data structure in which we store data as a collection in memory and then the data can be read from anywhere in the collection using indexes. Where the indexes are simply offsets to the base value or the memory location of first item.

As we can see in the image above showing how arrays are stored in the memory. All the items of an array has an incrementing index value that is used as reference.

Basic Terminologies of Array:

  • Array Index: The array index is the reference used to access values stored in the array. Every item in an array has a unique index attached to it. While some languages allow arrays with non-numeric indexes also referred as keys, In Rust the array index is only numeric, starting from 0.

  • Array Element: An array element is a value stored in an array. So by this definition, an array is a collection of array elements with each element having unique index.

  • Array Length: The array length or size of an array simply represents the number of elements in an array.

Creating Array

// initialization
int bar[3] = {25,58,14};

Accessing Array Elements

// accessing array elements
int bar[3] = {25,58,14};
cout << bar[1]; // outputs 58

Getting Array Length

// getting integer array size
int bar[3] = {25,58,14};
cout << sizeof(bar); // outputs 12

You might be wondering why did we get 12 instead of 3 because there are 3 elements in the array right? Well, the answer is the sizeof function returns the size of array in bytes. As the array is of type int, we need to divide it by the number of bytes one integer takes.

int bar[3] = {25,58,14};
int arrayLength = sizeof(bar) / sizeof(int);
cout << arrayLength; // outputs 3

As the size of int is mostly 4 bytes. Dividing 12 bytes with 4 resulted in the number of elements in the array. I know it's more complex than many other languages but still, this is how we determine the size of an array in C++.

That's all for arrays, now let's move on to Linked Lists...