Array In C

Posted on November 11, 2023 by Vishesh Namdev
Python C C++ Javascript Java
C Programming Language

Array is a collection of elements of the same data type, stored in contiguous memory locations. Arrays provide a convenient way to store and manipulate a group of data items under a single name. Each element in an array can be accessed using an index, and C arrays are zero-indexed, meaning the first element has an index of 0, the second element has an index of 1, and so on.

Array Indincs in C

Declaration of Arrays

In C, you can declare an array by specifying the data type of its elements, followed by the array name and the size of the array within square brackets. Here's the general syntax for declaring an array in C:

data_type array_name [ array_size ];
Example Array Declaration:
int numbers [ 10 ]; // Declares an integer array named 'numbers' with 10 elements.
double prices [ 5 ]; // Declares a double-precision floating-point array named 'prices' with 5 elements.
char message [ 100 ]; // Declares a character array named 'message' with space for 100 characters.

Keep in mind that once you've declared an array with a specific size, that size cannot be changed during the program's execution. If you need a dynamic data structure that can resize itself, you might consider using data structures like linked lists or dynamic arrays (created using pointers and memory allocation functions).

Initialization of Arrays

In C, you can initialize an array at the time of declaration by providing the initial values within curly braces {}. Here's how you can initialize an array in C:

data_type array_name [ array_size ] = { value1, value2, value3, ... };
Example of Array Declaration:
int myArray [ 5 ] = { 1, 2, 3, 4, 5 }; // Initializes an integer array with specific values

char greeting [] = { "Hello" }; // Initializes a character array 'greeting' with the string "Hello". The size is inferred.

Alternatively, you can partially initialize an array, and the remaining elements will be initialized to zero:

Accessing Array Elements:

When we create the array, we can also give it some starting values right away. We do this by making a list of those values inside curly braces { } and separating them with commas. This list is called an initializer list.

Array in C Programming

You can access individual elements of an array using the square bracket notation:

Example for Accessing an Array :
int element = myArray [ 2 ]; // Accesses the third element (index 2)

Note:

1. Arrays in C have a fixed size, which is determined at the time of declaration.

2. Array indices start from 0, so the first element is at index 0, the second at index 1, and so on.

3. Accessing elements with an index outside the array's bounds can lead to undefined behavior and should be avoided.

4. C does not provide built-in bounds checking for array access, so it's important to be cautious to prevent buffer overflows.