Array is the simplest form of collection. In an array, elements are places sequentially one after another. We can easily find the nth(starting from 0) element by offset as array[n].
Array can be of primitive type like int, char, long etc or can be of user defined type like struct and union. User needs to provide a non-negative constant size for the array. This size cannot be any variable.
Syntax for declaring an array is -
<type> <array name> [<size>];
int index ; //array of 10 elements of type integer
typedef struct student_t_
student_t student ; //array of 100 elements of type struct student_t
typedef struct mouse_param_t_
unsigned char button;
unsigned char x;
unsigned char y;
typedef union mouse_event_t_
unsigned char buffer;
mouse_event_t m_event ; //array of 2 elements of type union mouse_event_t
int size = 10;
int index [size]; //size is a varibale, so not allowed
const int size = 10;
int index [size]; //size is a constant, so allowed
int total_size = sizeof (index); //here size will be sizeof(each element) * element count
student_t students_ptr = (student_t *) malloc (sizeof (*students_ptr) * count);
for (int i = 0; i < sizeof(student)/sizeof(student); i++)
access student [i]
for (int i = 0; i < 100; i++)
access student [i]
Please note : i starts from 0 to 99, student  is 101 element,
this is array an element in out of bound of this array.
Character array is often used as string in C. Array has many other applications in many fields of data structure.
It has some advantages over linked list. Let's compare between array and linked list here.
It is very easy to implement. Thus code complexity is low.
Finding nth element does not need any iteration (order of O(1)), thus it is the fastest.
Array needs to be a predefined size. We cannot allocate one extra element at the runtime.
We cannot delete any element from start or middle.
Memory is wasted when we have more than enough elements what we are currently using.
LIFO example using array:
Array can be used in data structure in many ways. Dynamic array is one of mostly used example. We used some preallocated memory chunk to implement this mechanism.
In the following example we have items pointer to hold the array elemnts. Here max_cnt is the total number of count of this array. initially last_cnt will be -1.
This means this collection is empty. addelement call will increment the last_cnt ++ by one at a time untill it reachs max_cnt. last_cnt = (max_cnt - 1) means no further elemnts can be added in this collection and this is full.
Elemnts can be deleted at the end. delelement will discard last element and decrement last_cnt-- by one untill it becomes empty. This way array can be used to implement one LIFO i.e last in first out.
typedef struct int_array_t
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.