liveBook · Manning

Variable-length array

As explained in Modern C

A variable-length array is a C array whose length is determined at run time and whose lifetime rules differ from those of ordinary automatic objects.

void f(int n) { double a[n]; } Here, a is a variable-length array (VLA) when n is not an integer constant expression. Its length is determined at run time, unlike a fixed-length array (FLA), whose length comes from an integer constant expression or an initializer. section 6.1.3

The declaration rules impose several practical boundaries:

Lifetime begins at the definition

For an ordinary non-VLA automatic object, lifetime starts when its scope is entered. For a VLA, lifetime starts only when execution encounters its definition and ends when its visibility scope is left. Consequently, code earlier in the same block cannot use a pointer to that VLA: its storage cannot exist before the run-time size is known. section 13.3

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


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":9}],[{\"line\":1,\"ch\":3},{\"line\":1,\"ch\":9}],[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":9}],[{\"line\":1,\"ch\":3},{\"line\":1,\"ch\":9}]]"}
!@%STYLE%@!

Compare omitted-length arrays whose initializers determine their lengths: E and F are fixed-length double[4] arrays, not VLAs. section 6.1.3

How Modern C covers it

How deep it goes
Defines classification, restrictions, length calculation, and lifetime, but defers broader storage details.
Examples
Uses initializer-sized arrays, a sizeof-based length formula, and a control-flow example contrasting VLA and non-VLA lifetime.
What it assumes
Assumes array declarations and integer constant expressions while distinguishing initializer-based sizing from run-time sizing.
What you can do after
Apply C declaration rules to classify arrays, calculate array length, and reason about when VLA storage is valid.
How it connects
Connects array declarations with integer constant expressions, initializers, sizeof, object lifetime, and visibility scope.

Also explained in

Compare how 2 books explain variable-length array →

Related concepts

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