CC · Lesson 5 of 8

Arrays & Strings

In C, a string is just an array of characters ending with a null byte (\0). This is either elegant or terrifying. Reader's choice.

C
#include <stdio.h>
#include <string.h>

int main() {
    // Arrays — fixed size, all same type
    int numbers[5] = {10, 20, 30, 40, 50};
    printf("%d\n", numbers[0]);    // 10
    printf("%d\n", numbers[4]);    // 50

    // Partial initialization — rest is zero
    int data[10] = {1, 2, 3};  // data[3..9] = 0

    // Iterate
    int len = sizeof(numbers) / sizeof(numbers[0]);  // common idiom
    for (int i = 0; i < len; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    // 2D arrays
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    printf("Center: %d\n", matrix[1][1]);  // 5

    // Strings — char arrays ending with '\0'
    char greeting[] = "Hello";     // compiler adds '\0'
    char name[50] = "World";       // 50-byte buffer

    printf("%s\n", greeting);      // Hello
    printf("Length: %zu\n", strlen(greeting));  // 5 (not counting '\0')

    // String functions from <string.h>
    char full[100];
    strcpy(full, greeting);        // copy greeting into full
    strcat(full, ", ");            // append
    strcat(full, name);            // append
    strcat(full, "!");
    printf("%s\n", full);          // Hello, World!

    printf("%d\n", strcmp("abc", "abc"));  // 0 — strings are equal
    printf("%d\n", strcmp("abc", "xyz"));  // negative — abc < xyz

    return 0;
}
⚠ Warning
Buffer overflows are C's most famous security vulnerability. Never use strcpy() with untrusted input — use strncpy() or snprintf() instead. Always make sure your buffers are large enough for the data plus the null terminator.