On this page
  1. Arrays & C Strings
  2. Contents
  3. Array-to-Pointer Decay
  4. NUL-Terminated C Strings

Arrays & C Strings

Prev: Control Flow & Functions | Up: fundamentals | Next: Structs, Unions & Enums
Rel: Pointers & Pointer Arithmetic, stdlib & string.h
Ref: cppreference — C Arrays
Tags: #public #prog #c #fundamentals #strings


Contents


Array-to-Pointer Decay

In most expressions (including passing to a function), an array int a[10] decays to a pointer to its first element (int *), losing its length. Always pass (const T *ptr, size_t len) together:

#include <stddef.h>

static int sum_array(const int *arr, size_t len) {
    int total = 0;
    for (size_t i = 0; i < len; i++) {
        total += arr[i];
    }
    return total;
}

Within the defining scope only (before decay), element count is sizeof(a) / sizeof(a[0]).


NUL-Terminated C Strings

A C string is a char array terminated by a '\0' byte. String literals ("hello") live in read-only memory — always bind them to const char *.

Linked from

Related notes