liveBook · Manning

Array length

As explained in Modern C, Third Edition

Array length is the number of elements contained in an array object.

An array’s length is its number of elements. For an array object A, calculate it with `(sizeof A) / (sizeof A[0])`: divide the object’s total size by one element’s size. An omitted bound can be determined from an initializer when the initializer’s structure is known at compile time. section 6.1.3

Keep these distinctions explicit:

  • If the bound is not an integer constant expression, the array is a variable-length array (VLA). VLA support has changed across C standards. section 6.1.3
  • A pointer does not retain the length of the array object behind it; pointer-based functions must receive the real length separately. section 11.1.2
  • Array-parameter notation such as `double const a[len]` clarifies the expected element count, even when the interface passes through a pointer. section 11.1.2

Passing a length with a pointer

For `double A[7]`, a function can sum the whole array with `sum0(7, &A[0])`, the last six elements with `sum0(6, &A[1])`, or three middle elements with `sum0(3, &A[2])`. The pointer identifies a starting element; `len` identifies how many elements to process. section 11.1.2

double E[] = { [3] = 42.0,  [2] = 37.0, };
double F[] = { 22.0,  17.0, 1, 0.5, };

Compare an omitted array bound inferred from a designated initializer with an explicitly inferred four-element array. section 6.1.3

How Modern C, Third Edition covers it

How deep it goes
Explains sizeof-based calculation, VLA classification, and pointer-interface limits, but does not develop deeper array representation mechanics.
Examples
Uses inferred-bound initializers, sizeof division, pointer-based summation, and subarray calls carrying explicit lengths.
What it assumes
Assumes familiarity with C arrays, initializers, pointers, functions, and the sizeof operator.
What you can do after
Apply it via sizeof for array objects and pass explicit lengths when processing arrays through pointers.
How it connects
Connects array length with arrays, variable-length arrays, sizeof, pointers, pointer addition, and function parameters.

Also explained in

Compare how 2 books explain array length →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.