Arrays in C

Our first example demonstrates the use of arrays in C. Arrays are a fundamental data structure that allow you to store multiple elements of the same type in contiguous memory locations.

#include <stdio.h>

int main() {
    // Here we create an array 'a' that will hold exactly 5 ints.
    // By default, the array is not initialized, which means it may contain
    // garbage values.
    int a[5];
    printf("emp: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");

    // We can set a value at an index using the array[index] = value syntax,
    // and get a value with array[index].
    a[4] = 100;
    printf("set: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
    printf("get: %d\n", a[4]);

    // In C, we use the sizeof operator to get the size of an array in bytes.
    // To get the length, we divide it by the size of a single element.
    printf("len: %lu\n", sizeof(a) / sizeof(a[0]));

    // Use this syntax to declare and initialize an array in one line.
    int b[] = {1, 2, 3, 4, 5};
    printf("dcl: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", b[i]);
    }
    printf("\n");

    // C doesn't have a built-in way to resize arrays or count elements automatically.
    // You need to manage the size manually.

    // Array types are one-dimensional, but you can create multi-dimensional
    // arrays by nesting them.
    int twoD[2][3] = {{1, 2, 3}, {4, 5, 6}};
    printf("2d: ");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", twoD[i][j]);
        }
    }
    printf("\n");

    return 0;
}

To compile and run this program:

$ gcc -o arrays arrays.c
$ ./arrays
emp: 0 0 0 0 0 
set: 0 0 0 0 100 
get: 100
len: 5
dcl: 1 2 3 4 5 
2d: 1 2 3 4 5 6 

Note that arrays in C have some differences compared to other languages:

  1. Arrays in C are zero-indexed.
  2. C doesn’t perform bounds checking on array accesses, so you need to be careful not to access elements outside the array’s bounds.
  3. The size of an array must be known at compile time, unless you’re using dynamic memory allocation.
  4. When you pass an array to a function, it decays to a pointer to its first element.

Understanding these characteristics is crucial for effective use of arrays in C programming.