Array is a term used for the collection of similar data type elements.
An array is a secondary data type derived from fundamental.It must have data type int, char, double float, struct or union but every element under an array identifier must have the similar data type.
Suppose we required 5 integer elements in a program then there are two ways to allocate memory:
— Declare 5 different variables to store data.
— Declare an array to store 5 values under a single variable name.
datatype array_Variable_Name[Max_Element_Count];
Pronounce above declaration as “arr_num is an array of 5 integer datatype elements”.
int = array elements data type
arr_num= array variable or identifier
[5]=number of elements
Pronounce above declaration as “arr_var is an array of 5 character type elements”.
char = array elements data type
arr_var= array variable or identifier
[5]=number of elementsPronounce above declaration as “arr_var is an array of 5 float or decimal datatype elements”.
float= array elements data type
arr_var= array variable or identifier
[5]=number of elementsPronounce above declaration as “emp is an array of 5 employee type structure”.
struct employee = data type
emp= structure variable/identifier
[5]=number of elementsA declared array may have some garbage data at the allocated memory location. So to be on safe side it is best practice to initialize the array with zero value at the time of declaration.
datatype array_Variable_Name[Max_Element_Count]={val1,val2,val3,…….valn};
OR
datatype array_Variable_Name[ ]={val1,val2,val3,…….valn};
In Syntax 1 Number of elements in the array cannot exceed beyond the declared Max_Element_Count so
array size = Max_Element_Count*sizeof(dataType).
In Syntax 2 Number of elements in the array is not fixed so the size of the array will be-
array size=number of initialized array elements*sizeof(dataType).
— Initialize an array of 5 integer datatype elements with value 10,20,30,40,50.
— Declare An array of 5 character datatype elements.
— Declare An array of 5 decimal datatype elements.
— Declare An array of structure for 5 employee information.
You can see the difference between the continuous addresses is 1 byte because the array is char data type and char data type size is 1 byte, for int and float it will be 4 bytes because of their memory size.
When compiling this program, compiler will execute program with following warning-
See the output.Data is correct till 5 elements and after that, some garbage values received because array reserved memory only for 5 elements.
Note: Sometimes it causes segmentation fault also.
So you can understand Array size calculation like this –
size of arr = size*sizeof(int) = 5 X 4 = 20