What is array in C programming language

What is Array in C Programming Language

Array in C programming language is a collection of fixed size data belongings to the same data type. An array is a data structure which can store a number of variables of same data type in sequence. These similar elements could be of type int, float, double, char etc.

Important points about Arrays in C:

  • An array is a collection of variables of same data types.
  • All elements of array are stored in the contiguous memory locations.
  • The size of array must be a constant integral value.
  • Individual elements in an array can be accessed by the name of the array and an integer enclosed in square bracket called subscript/index variable like employeeSalary[5].
  • Array is a random access data structure. you can access any element of array in just one statement.
  • The first element in an array is at index 0, whereas the last element is at index (size_of_array – 1).

What are advantages and disadvantages of Arrays in C

Advantage of Arrays in C

  • Less amount of code : Using array we can aggregate N variables of same data type in a single data structure. Otherwise we have to declare N individual variables.
  • Easy access of elements : We can access any element of array using array name and index. We can access all elements serially by iterating from index 0 to size-1 using a loop.
  • Easy to implement algorithms : Certain algorithms can be easily implemented using array like searching and sorting, finding maximum and minimum elements.
  • Random Access : We can access any elements of array in O(1) time complexity.

Disadvantages or Limitations of Arrays in C

  • Array is Static Data Structure. We cannot change the size of array in run-time.
  • We must know in advance that how many elements are to be stored in array.
  • Only elements of same data types can be stored in an array. We cannot store elements of multiple data types in a single array.
  • As Array elements are stored in consecutive memory locations. So, insertions and deletions of an element is time consuming as we have to shift other elements one position ahead or back respectively.
  • C doesn’t perform any array index bound checking. In and array of size N, you can write code to access N+5th element without getting error. When we try to access elements from outside of array boundaries, we will get garbage value.
  • As we cannot change the size of an array, developers generally declares large arrays to handle any future data expansion. This ends up in creating large arrays, where most of the space is unused.

Can we use negative array indexes in C, like marks[-2]

No, We cannot use negative array indexes. Remember array indexing starts from 0. Nth element in array is at index N-1.