Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures. However, in order to be stored together in a single array, all the elements should be of the same data type. The elements are stored from left to right with the left-most index being the 0th index and the rightmost index being the (n-1) index.
Array in C are of two types; Single dimensional arrays and Multidimensional arrays.
- Single Dimensional Arrays: Single dimensional array or 1-D array is the simplest form of arrays that can be found in C. This type of array consists of elements of similar types and these elements can be accessed through their indices.
- Multi-dimensional Arrays: The most common type of multi-dimensional array that is used in the C language is a 2-D array. However, the number of dimensions can be more than 2 depending upon the compiler of the user’s system. These arrays consist of elements that are array themselves.
Why Do We Need Arrays?
If we have a small number of elements, let us say we want 3 variables, then we can declare them separately like var1, var2, and var3. But if we have a large number of variables then we can use arrays to store them.
Let us take a real-life example. Suppose you want to make a program that prints 1-100 digits. Now in C language, you can achieve this by 2 methods. The first one is to make 100 variables and store the numbers from 1-100 in those variables separately and then print each digit. The second method is to create an array of size 100 and store the numbers in that array using a loop. These digits can be printed using a single loop in linear complexity. It is clear that the second method is more optimized and desirable than the first one as it is more convenient to store these values in a single array rather than creating 100 variables.
Declaration and Initialization of Array in C
There are various ways in which an array can be declared and initialized in various ways. You can declare an array of any data type (i.e. int, float, double, char) in C. The following ways can be used to declare and initialize an array in C.
-
Array Declaration by Specifying the Size
Arrays can be declared by specifying the size or the number of array elements. The size of the array specifies the maximum number of elements that the array can hold. In the latest version of C, you can either declare an array by simply specifying the size at the time of the declaration or you can provide a user-specified size. The following syntax can be used to declare an array simply by specifying its size.
// declare an array by specifying size in [].
int my_array1[20];
char my_array2[5];
// declare an array by specifying user defined size.
int size = 20;
int my_array3[size];
When an array is declared without allocating any value, then it stores a garbage value. If you access any uninitialized array value, then just like any uninitialized variable, it will give you a garbage value.
-
Array Declaration by Initializing Elements
An array can be initialized at the time of its declaration. In this method of array declaration, the compiler will allocate an array of size equal to the number of the array elements. The following syntax can be used to declare and initialize an array at the same time.
// initialize an array at the time of declaration.
int my_array[] = {100, 200, 300, 400, 500}
In the above syntax, an array of 5 elements is created and even though the array size has not been specified here, the compiler will allocate a size of 5 integer elements.
-
Array Declaration by Specifying the Size and Initializing Elements
An array can also be created by specifying the size and assigning array elements at the time of declaration. This method of array creation is different from the previous one. Here, if the number of initialized elements is less than the size of the array specified, then the rest of the elements will automatically be initialized to 0 by the compiler. See the following syntax to understand this.
// declare an array by specifying size and
// initializing at the time of declaration
int my_array1[5] = {100, 200, 300, 400, 500}; // my_array1 = {100, 200, 300, 400, 500}
//
int my_array2[5] = {100, 200, 300}; // my_array2 = {100, 200, 300, 0, 0}
In the above array syntax, my_array1 is an array of size 5 with all five elements initialized. Whereas, my_array2 is an array of size 5 with only three of its elements initialized. The remaining two elements of the second array will be initialized to 0 by the compiler.
-
Array Initialization Using a Loop
An array can also be initialized using a loop. The loop iterates from 0 to (size – 1) for accessing all indices of the array starting from 0. The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.
// declare an array.
int my_array[5];
// initialize array using a “for” loop.
int i;
for(i = 0; i < 5; i++)
{
my_array[i] = 2 * i;
}
// my_array = {0, 2, 4, 6, 8}
In the above syntax, an array of size 5 is declared first. The array is then initialized using a for loop that iterates over the array starting from index 0 to (size – 1).
Access Array Elements
Since an array is stored contiguously in the memory, it has indices starting from ”0” to “array_size – 1”, also known as zero-based indexing. This indexing represents the position in the array.
The array indices are used to access any element of the array in the following way:
array_name[index]
The index of the element to be accessed is specified within square brackets “[]”. The range of the index is- integers in the range [0, size).
Examples:
int my_array[6];
// access 1st element
my_array[0] = 100;
// access 4th element
my_array[2] = 300;
// access last element
my_array[5] = 600;
Input and Output Array Elements
Array values can be stored by taking input from the user and storing them in the array. The following example illustrates this:
// input an integer element and store it
// in 1st position of the array
scanf(“%d”, &my_array[0]);
// input a float element and store it
// in ith position of the array
scanf(“%f”, &my_array[i-1]);
Similarly, array elements can also be displayed in the output using the printf() method. The index is specified indicating the position of the element to be printed. The following example illustrates this:
// print the element stored at 1st position or 0th index
printf(“%d”, my_array[0]);
// print the element stored at ith position or (i – 1)th index
printf(“%d”, my_array[i-1]);
Advantages of Array in C
Arrays have a great significance in the C language. They provide several advantages to the programmers while programming. Some of them are:
- Arrays make the code more optimized and clean since we can store multiple elements in a single array at once, so we do not have to write or initialize them multiple times.
- Every element can be traversed in an array using a single loop.
- Arrays make sorting much easier. Elements can be sorted by writing a few lines of code.
- Any array element can be accessed in any order either from the front or rear in O(1) time.
- Insertion or deletion of the elements can be done in linear complexity in an array.
Disadvantages of Array in C
Every advantageous thing comes with some disadvantages as well. This stands true for arrays as well. Below are some of the disadvantages of the array in C:
- Accessing an array out of bounds: The first disadvantage of arrays is that they are statically allocated. This means that once their size is initialized, it can not be increased or decreased. To understand this point, consider the example given below:
#include <stdio.h>
int main()
{
//declaring the array of size 20
int my_array[20];
//initialising the array elements
for (int i = 0; i < 20; i++)
{
//i will be the value of e
//very ith element of the array
my_array[i] = i;
}
// Print value at index 5 of the array
printf(“Element at index 5”
” is %dn”,
my_array[5]);
// Print value at index 13 of the array
printf(“Element at index 13”
” is %dn”,
my_array[13]);
// Print value at index 21 of the array
printf(“Element at index 21”
” is %d”,
my_array[21]);
return 0;
}
In the above example, the initial value of the array arr is 20, so by printing the value of elements up to the index 20, we are getting the desired output. But when we try to print the element at the 21st index, it is giving a garbage value. This is because the array was accessed out of the bound index.
This issue can be resolved using malloc() and calloc() functions. These functions allocate the memory dynamically. We have a free() function that allows us to free the unwanted memory at our will. The below example illustrates the same:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//*ptr will be storing the base
//address of the array elements
int *ptr;
int size, i;
// size of the array will be 5
size = 5;
printf(“Size of the array is: %dn”, size);
// allocating the array memory
//dynamically using malloc()
ptr = (int *)malloc(size * sizeof(int));
// Checking whether the memory has
//been successfully allocated by malloc
if (ptr == NULL)
{
printf(“Memory has not been allocated allocatedn”);
exit(0);
}
else
{
// Memory has been successfully allocated
printf(“Memory has been allocated successfullyn”);
// initializing the array elements
for (i = 0; i < size; ++i)
{
ptr[i] = i + 1;
}
// Print the elements of the array
printf(“The elements of the array are: “);
for (i = 0; i < size; ++i)
{
printf(“%d “, ptr[i]);
}
}
return 0;
}
- Homogeneity: We can store only a single type of element in the array i.e., arrays are homogeneous. We can not use it as a template. For example, if the array data type is char, then only characters can be stored in the array. If you try to store integers or any other element of a different data type, it will throw an error. To understand this point, consider the example given below:
#include <stdio.h>
int main()
{
// such declaration will throw
// Compilation Error
int my_array[6] = {1, 2, “mango”, 4, 5, 6.2};
int i;
printf(“Elements of the array are: “);
for (i = 0; i < 6; i++)
{
printf(“%d “, my_array[i]);
}
return 0;
}
In the above example, the data type of the array is int. But when we try to declare string and float values to the array, it throws a compilation error.
This issue can be resolved by creating a structure to store heterogeneous (non-homogeneous) values. Consider the below example to understand this concept:
#include <stdio.h>
// create a structure
struct example
{
int fruit_quant;
float fruit_rate;
char fruit_name[30];
};
int main()
{
// s1 – object of the structure
struct example s1 = {10, 90.45, “Mango”};
// accessing structure members
// using structure object
printf(“%dn”, s1.fruit_quant);
printf(“%fn”, s1.fruit_rate);
int i;
for (i = 0; s1.fruit_name[i] != ‘