Share:
Notifications
Clear all

What is an array in C

1 Posts
1 Users
0 Reactions
708 Views
(@kajal)
Posts: 299
Reputable Member
Topic starter
 

An array is a collection of elements, all of the same type, stored in contiguous memory locations. It allows you to store multiple values of the same data type under a single variable name. Arrays are used when you need to store a fixed number of values of the same type and access them using an index.

Key Characteristics of Arrays in C:

  1. Fixed Size: The size of the array must be defined at compile time, and it cannot be changed during program execution.
  2. Zero-based Indexing: Array indices start from 0. For an array of size n, the valid indices are 0 to n-1.
  3. Homogeneous: All elements in an array must be of the same data type, such as all integers or all floats.

Syntax for Declaring an Array:

data_type array_name[array_size];
  • data_type: The type of data (e.g., int, float, char).
  • array_name: The name of the array.
  • array_size: The number of elements the array will hold.

Example:

int numbers[5]; // Declares an array of 5 integers

Here, numbers is an array that can store 5 integers. You can access these integers using indices from 0 to 4.

Initializing an Array:

You can initialize an array at the time of declaration.

Example 1: Explicit Initialization

int numbers[5] = {1, 2, 3, 4, 5};

Example 2: Implicit Initialization (Size Determined Automatically)

int numbers[] = {1, 2, 3, 4, 5}; // Compiler automatically sets size to 5

Example 3: Partially Initializing an Array

int numbers[5] = {1, 2}; // The remaining elements will be initialized to 0

Accessing Array Elements:

You can access or modify elements in the array by using the index of the element. The index starts at 0.

Example:

int numbers[5] = {1, 2, 3, 4, 5}; printf("%d", numbers[2]); // Output will be 3, as array indices start at 0 numbers[2] = 10; // Modifies the third element (index 2) printf("%d", numbers[2]); // Output will now be 10

Multi-dimensional Arrays:

C also allows multi-dimensional arrays, where you can create arrays of arrays. The most common example is a 2D array (array of arrays), often used to represent matrices or grids.

Example of 2D Array:

int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

Here, matrix is a 2D array with 3 rows and 3 columns. To access an element, you need to specify both row and column indices:

printf("%d", matrix[1][2]); // Output will be 6 (second row, third column)

Important Notes:

  • Array Bounds: Accessing an array with an index outside of its defined range results in undefined behavior, which can lead to errors or unexpected results.
  • Array Size: In C, the size of an array is fixed once defined, and this cannot be changed dynamically (unless using dynamic memory allocation, e.g., malloc()).
 
Posted : 16/03/2025 9:19 pm
Share: