liveBook · Manning

Array parameter

As explained in Modern C, Third Edition

An array parameter is a function parameter declared with array notation whose array-bound information is adjusted or lost when used in a function definition or call.

An array parameter uses array notation in a function interface, but C rewrites it to a pointer. The innermost array dimension is therefore lost, and the function operates on the caller’s elements rather than a copied array. section 6.1.4 section 11.3.2

Swapping elements through an array parameter

void swap_double(double a[static 2]) { a[0] and a[1] are exchanged; } Calling swap_double(A) changes A directly. The declaration is equivalent in parameter type to a pointer form, while preserving useful array-sized interface notation. section 11.3.2

TAKEAWAY rules:

  • Do not use sizeof on an array parameter; it does not retain the array object’s size. section 6.1.4
  • Expect only the innermost dimension to rewrite; multidimensional parameters retain subsequent dimensions as pointer-to-array types. section 11.3.2
  • Prefer array notation when the parameter represents a non-null array and document its expected length when possible. section 11.3.2
void matrix_mult(size_t n, size_t k, size_t m,
                 double       C[n][m],
                 double const A[n][k],
                 double const B[k][m]) {
   for (size_t i = 0; i < n; ++i) {
     for (size_t j = 0; j < m; ++j) {
       C[i][j] = 0.0;
       for (size_t l = 0; l < k; ++l) {
         C[i][j] += A[i][l]*B[l][j];
       }
     }
   }
}

Matrix multiplication demonstrates array notation for multidimensional parameters, with dimensions supplied before the arrays. section 11.3.2

How Modern C, Third Edition covers it

How deep it goes
Explains pointer rewriting and multidimensional bounds, but defers the underlying mechanism until pointers are introduced.
Examples
Demonstrates element swapping, array copying, matrix multiplication, equivalent pointer declarations, and incompatible pointer-to-pointer matrices.
What it assumes
Assumes basic function and array syntax, while postponing the pointer mechanics that explain parameter rewriting.
What you can do after
Apply it via C function interfaces that access one-dimensional or multidimensional arrays without expecting array-value copying.
How it connects
Connects array parameters with pointers, array decay, multidimensional arrays, variable-length arrays, and function declarations.

Also explained in

Compare how 2 books explain array parameter →

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.