Arrays in C

Arrays in C are collections of variables of the same type stored in contiguous memory locations. They allow efficient storage and manipulation of multiple data items using a single variable name with indices.

1. Types of Arrays

C supports single-dimensional, multi-dimensional, and dynamic arrays.

  • Single-dimensional array: List of elements in a single row.
  • Two-dimensional array: Elements arranged in rows and columns.
  • Three-dimensional array: Elements in 3D format (like a cube).
  • Dynamic array: Size allocated at runtime using pointers.
  • Pointer arrays: Array of pointers pointing to variables or other arrays.
  • Constant arrays: Arrays whose values cannot be changed after initialization.

2. Single-Dimensional Array

A single-dimensional array stores elements linearly and is accessed using a single index.

  • Example: int arr[5] = {1, 2, 3, 4, 5}; printf("%d", arr[2]); // Output: 3

3. Two-Dimensional Array

A two-dimensional array stores data in rows and columns and is accessed using two indices.

  • Example: int matrix[2][3] = {{1,2,3},{4,5,6}}; printf("%d", matrix[1][2]); // Output: 6

4. Three-Dimensional Array

A three-dimensional array stores elements in a 3D structure and is accessed using three indices.

  • Example: int cube[2][2][2] = {{{1,2},{3,4}},{{5,6},{7,8}}}; printf("%d", cube[1][0][1]); // Output: 6

5. Dynamic Arrays

Dynamic arrays allocate memory at runtime using pointers and functions like malloc or calloc.

  • Example: int *arr = (int*) malloc(5 * sizeof(int)); arr[0] = 10; arr[1] = 20;

6. Pointer Arrays

Pointer arrays are arrays of pointers that can point to variables, arrays, or strings.

  • Example: char *names[] = {"Alice", "Bob", "Charlie"}; printf("%s", names[1]); // Output: Bob

7. Constant Arrays

Constant arrays are declared using the const keyword. Their values cannot be changed after initialization.

  • Example: const int arr[3] = {1,2,3}; // arr[0] = 5; // Error: cannot modify a const array