Back to Curriculum

Arrays and Strings

📚 Lesson 5 of 15 ⏱️ 45 min

Arrays and Strings

45 min

Arrays in C store multiple values of the same type in contiguous memory locations. Arrays enable efficient storage and access of related data. Array elements are accessed using indices starting from 0. Arrays can be one-dimensional (vectors) or multi-dimensional (matrices, tables). Understanding arrays is essential for working with collections of data in C.

Array declaration specifies the type, name, and size. Arrays can be initialized with values at declaration or left uninitialized. Array size must be a compile-time constant (or variable-length arrays in C99+). Arrays are passed to functions as pointers, so size information is typically passed separately. Understanding array declaration enables proper array usage.

Strings in C are arrays of characters terminated by the null character ('\0'). String literals are automatically null-terminated. String manipulation functions from string.h (strlen, strcpy, strcat, strcmp) operate on null-terminated character arrays. Understanding strings enables text processing in C programs.

Array indexing uses square brackets with zero-based indices. The first element is at index 0, and the last element is at size-1. Out-of-bounds access causes undefined behavior, making bounds checking important. Understanding array indexing enables safe array access.

Multi-dimensional arrays represent tables or matrices. Two-dimensional arrays are arrays of arrays, enabling row and column access. Multi-dimensional arrays are stored in row-major order (all elements of a row are contiguous). Understanding multi-dimensional arrays enables working with structured data.

Array operations include traversal (visiting all elements), searching (finding specific values), sorting (ordering elements), and manipulation (modifying elements). Arrays can be passed to functions, but size information must be handled carefully. Understanding array operations enables effective data processing.

Key Concepts

  • Arrays store multiple values of the same type in contiguous memory.
  • Array indexing starts at 0 and uses square brackets.
  • Strings are null-terminated character arrays.
  • Multi-dimensional arrays represent tables or matrices.
  • Arrays are passed to functions as pointers.

Learning Objectives

Master

  • Creating and initializing arrays
  • Accessing and modifying array elements
  • Working with strings and string functions
  • Using multi-dimensional arrays

Develop

  • Understanding memory layout and arrays
  • Implementing array algorithms
  • Working with text data in C

Tips

  • Initialize arrays: int arr[5] = {1, 2, 3, 4, 5};
  • Access elements: arr[0] for first element, arr[size-1] for last.
  • Use string functions: strlen(), strcpy(), strcat(), strcmp() from string.h.
  • Pass array size: functions need size parameter for arrays.

Common Pitfalls

  • Accessing out of bounds, causing undefined behavior or crashes.
  • Forgetting null terminator in strings, causing string function errors.
  • Not passing array size to functions, unable to iterate safely.
  • Confusing array indexing (0-based), causing off-by-one errors.

Summary

  • Arrays enable efficient storage of multiple values.
  • Strings are null-terminated character arrays.
  • Array indexing is zero-based.
  • Understanding arrays enables working with collections of data.

Exercise

Demonstrate array operations and string manipulation.

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

int main() {
    // One-dimensional array
    int numbers[5] = {1, 2, 3, 4, 5};
    
    printf("Array elements: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("
");
    
    // Two-dimensional array
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    
    printf("Matrix:
");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("
");
    }
    
    // String operations
    char str1[] = "Hello";
    char str2[] = "World";
    char result[50];
    
    strcpy(result, str1);
    strcat(result, " ");
    strcat(result, str2);
    
    printf("Concatenated string: %s
", result);
    printf("Length: %lu
", strlen(result));
    
    // String comparison
    if (strcmp(str1, str2) == 0) {
        printf("Strings are equal
");
    } else {
        printf("Strings are not equal
");
    }
    
    // Character array manipulation
    char name[] = "John Doe";
    printf("Original: %s
", name);
    
    // Convert to uppercase
    for (int i = 0; name[i] != ''; i++) {
        if (name[i] >= 'a' && name[i] <= 'z') {
            name[i] = name[i] - 32;
        }
    }
    printf("Uppercase: %s
", name);
    
    return 0;
}

Exercise Tips

  • Always null-terminate strings: ensure '\0' at end of character arrays.
  • Use strncpy() for safer copying: strncpy(dest, src, size) to prevent buffer overflow.
  • Check array bounds: validate indices before accessing array elements.
  • Use sizeof() for array size: sizeof(arr)/sizeof(arr[0]) for element count.

Code Editor

Output