Arrays
Arrays
Array
Tldr
Array is a:
It is used to assign variables in a bulk
Homogenous(Same Data Storing)
Contiguous (The data are stored in a serial order)
Random Access (All the elements, can be accessed randomly
from the array; as the elements are different)
Static (We need to have the size beforehand)
It is a homogeneous Data Structure, this means that all the items
inside of the Array is of the same data type
It is a contiguous block of memory of the same kind of data that is,
i.e. same: DataType
The syntax of array in C is like so:
int x10;
// DataType ArrayNameArraySize;
In the above definition of the array it is of int type (which means
that all the elements in this array is of the int DataType only)
The array is named as x The name of Array is the CONSTANT pointer
to the first element of that array; hence we can’t change this
pointer
After String:
#include <stdio.h>
int main(){
char x10;
x="ABC";
printf("%c",x6);
}
1/3
Arrays
And the array x has 10 elements that are ranging from 0-9
Even though it is contiguous memory allocation, by the virtue of how
arrays are stored it (the elements) can be accessed through the
random access
x2 → It will give us the 3rd element, the 2 here is the subscript
Array is a Static Data Structure, meaning that we have to give the
size beforehand (not on runtime)
Why do arrays always start from 0 ?
Well we want the elements to be accessible Randomly
Let’s say we want to access an element at the m position, th
with index starting from 0 this makes it very very easy for
us
We can say that the first element is stored at the location l
and each element will have a fixed size in the memory
depending on the DataType
Mathematically this is now very easy to find with just the
info about l and m
Address of element at m will be: Address = l + m ∗ size(DataT ype)
There are two types of Arrays:
1-D (or normal array)
2-D Array (or More Dimensional, but it is the same)
Initializing an Array
#include <stdio.h>
int main(){
int x100={5};
//Only the first element is 5, rest all are 0
printf("%d",x2);
return 0;
}
Important
There is no Array out of Bounds Error in C
Hence this will not cause an Error like it would in other
languages
2/3
Arrays
#include <stdio.h>
int main(){
int x100={5};
//Only the first element is 5, rest all are 0
printf("%d",x200);
return 0;
}
Error: Too Many Initializers
This is an error that occurs when we try to fit too many
elements into a array; say size ==3 but we try to put 4 elements
int x[3] = {1,2,3,4};
Well we can also initialize it like this
int x = {1,2,3} → The compiler automatically understands that this is
an Array of 3 elements only; Hence ensuring the static type is
maintained
Analogy if Any
Similarities:
Differences:
In what case does the Analogy Not make sense:
Is there a better Analogy:
Understanding the knowledge (Set Due Date)
Consumption
Digestion
3/3