YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Memory & dataChapter 24 of 73

Understanding arrays

Connect element counts, contiguous storage, initialization, indexing, and permitted one-past boundaries.

10 min readFoundationsC17 baseline
Offline reading
In this chapter9 sections
0% through this chapter

An array holds a fixed sequence of elements of one type. We will connect its element count, valid indexes, and layout before using it through a pointer. Knowing where the sequence ends is part of every valid access.

Need the ideas side by side? Open the concept guide.

1. An array has elements, order, and a bound

An array contains contiguous elements of its element type. int readings[3] defines three integer elements, with indices 0, 1, and 2. The bound is an element count, not the last valid index. Each element can be used much like another object of that type, while the complete array has its own array type and size.

  1. index 012
  2. index 115
  3. index 218
  4. index 3Boundary
Three int elements. The one-past boundary can be represented by a pointer, but it is not a fourth element. Cell width does not specify sizeof(int).
C17 · illustrative fragment
int readings[3] = {12, 15, 18};
readings[1] = 16;

A row of numbered lockers is a useful analogy: each position has a predictable neighbor. Its limit is that C does not put a guard at each locker. Ordinary array subscripting does not require an implementation to diagnose every out-of-bounds use. “The next address exists somewhere” does not make it an element of this array.

2. Initialization determines the starting values

C17 · illustrative fragment
int readings[4] = {12, 15};

When an initializer supplies fewer elements than this fixed-size array contains, the remaining integer elements are initialized to zero. That is a language initialization rule. An automatic array with no initializer does not get this promise: do not read its indeterminate elements before assigning suitable values. An array with static storage duration has zero initialization even without an explicit initializer.

An array object does not resize during its lifetime. Changing a variable that was used to compute a bound does not stretch an existing array. Allocated storage can later be replaced using allocation functions; that is a separate operation with its own lifetime and pointer rules. Arrays are not assignable as whole arrays, although individual elements may be modifiable and a containing structure can be copied under structure-assignment rules.

3. Pointer steps count elements

For a suitable pointer into an array, adding one advances to the next element, not universally to the next byte. An int * step corresponds to sizeof(int) bytes in the array representation; a char * step is one C byte. Valid subscripting satisfies a[i] meaning *(a + i). The index still has to identify a valid element for an access.

In the following expressions, the array name supplies a pointer to its first element. The next lesson explains that conversion and its important exceptions; the array object itself remains an array.

C17 · illustrative fragment
int readings[3] = {12, 15, 18};
int *end = readings + 3;
int total = 0;
for (int *current = readings; current != end; ++current) {
    total += *current;
}

The loop compares against a one-past pointer and stops before dereferencing it. The arithmetic must keep both the original and resulting pointer within the same array or its one-past position. Forming a farther pointer is already outside the rule; a later check does not undo that. Subtraction requires the same array or its one-past position and a result representable as ptrdiff_t.

4. A boundary is not an extra element

For three elements, reading or writing readings[3] is invalid; index 2 is the last element. A loop using i < count often matches this model, whereas i <= count often includes an extra access. The expression still needs correct integer types, a trustworthy count, and an array large enough for that count.

In a multidimensional array, each row is itself an array. Accessing past the end of one row is not made valid merely because another row follows in the larger object. We will use a pointer-to-row type when discussing how two-dimensional arrays connect to pointers.

5. Runtime-sized arrays still have rules

A variable-length array, where supported, can take an evaluated bound at runtime. Such a bound must be positive, and the size is fixed for that particular instance after evaluation. This does not mean the array automatically grows when more input arrives. Large automatic arrays can also exceed the execution environment’s available resources.

Primary references and further reading

An array is an object, not a pointer variable

Compare, follow, and explain this idea

An array contains a fixed number of elements of one type for that array instance. In many expressions its name is converted to a pointer to the first element. The conversion does not change the array object into a pointer object.

When this helps Use the distinction when finding a real array’s element count, passing array data to a function, and checking a subscript.

Read the ideas side by side

The array marks
marks has type array of 3 int. Its storage includes three int elements.
The pointer p
p has type pointer to int. It can be assigned a different pointer value.

An array expression often produces a pointer, but the two types are different.

sizeof marks
For this actual non-VLA array, this measures storage for all three elements.
sizeof p
This measures the pointer object, not the storage reachable through it.

The element-count formula needs the actual array, not a pointer parameter.

marks + 2
Points to the last element, which can be accessed while the array is alive.
marks + 3
Is the one-past position. It may mark an end but has no element to read.

A legal pointer position is not always a legal dereference position.

Follow the reasoning

This example uses an actual three-element array in one function. size_t is available from <stddef.h>.

C17 · illustrative fragments in the stated context

  1. int marks[3] = {3, 6, 9};
  2. size_t count = sizeof marks / sizeof marks[0];
  3. int *p = marks;
  4. int last = *(p + 2);
  5. int *end = marks + count;
  1. Initialize the array

    The elements marks[0], marks[1], and marks[2] hold 3, 6, and 9.

  2. Find the element count

    sizeof marks is three times sizeof marks[0], so the quotient is 3. No fixed byte size for int is needed.

  3. Initialize p

    In this initializer, marks converts to a pointer to its first element. p stores that pointer value.

  4. Access the last element

    p + 2 points to marks[2]. Dereferencing it reads 9.

  5. Form the end position

    marks + count is one past the array. The example forms and compares this pointer; it never dereferences it.

Common misconceptions

These statements are misleading. Open each one to see why.

MisconceptionThe array name is a pointer variable.

The array name designates the array object. Many uses convert its expression to a pointer value, but you cannot reassign the array itself with marks = p.

MisconceptionWriting int a[3] as a function parameter passes three copied elements.

An array parameter declaration is adjusted to a pointer parameter. The ordinary [3] spelling does not copy three elements or automatically carry their count.

MisconceptionAdjacent memory makes an out-of-range subscript valid.

Access must satisfy the array’s bounds. A nearby address or an apparently successful run does not create an extra element.

Go a little deeperOptional technical detail

The operator matters

For the actual array here, sizeof and unary & do not apply the usual array-to-pointer conversion. &marks has pointer-to-array type, while marks in the initializer for p produces pointer-to-int type.

Arrays of arrays keep their row type

For int grid[2][3], the usual conversion produces a pointer to a row of 3 int. It does not produce int **. Keep row bounds and the pointed-to type in the model.

C17 Array parameter adjustment and the one-past boundary apply in C17. Variable-length arrays have additional rules; this fixed-size example does not depend on them.

C23 C23’s typeof operators can preserve an array type instead of applying the usual conversion. Array parameters still adjust to pointer parameters; typeof on such a parameter sees its adjusted type.

Check the source rules

Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.

Say it in your own words

Why does the sizeof element-count formula work here but not for a pointer parameter?

Compare with an explanation

Here marks is the actual array. A pointer parameter has a pointer type, so sizeof measures that pointer rather than the caller’s array.

Before you move on

  • An array contains a contiguous sequence of elements of one type.
  • Valid indexes identify existing elements, while the one-past pointer is a boundary rather than an element.
  • Count and range information must remain consistent with the available storage.
Keep these ideas separate
Last element / One-past boundary
An array of n elements has indexes 0 through n−1; the n boundary cannot be dereferenced as an element.
Explain it in your own words

How would you explain the difference between an element count and the largest valid index?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

An array has three elements. What is its last valid element index?
Read the explanation for every choice
  1. 3

    Indices begin at zero, so index 3 would be outside the three elements.

  2. It depends on the first stored value.

    Element values do not change the indexing range.

  3. 2

    ✓ Correct reasoning. The element indices are 0, 1, and 2.

C17

Quick reference from the earlier edition

Retained for existing section links and saved passages. Read the expanded explanation above for the connected learning sequence.

Arrays

An array stores same-typed elements contiguously and does not resize during its lifetime. C does not automatically check subscripts; accessing outside the valid elements is undefined behavior. Multidimensional arrays use row-major order. C99 added variable-length arrays (VLAs), whose evaluated bounds must be positive; each bound is fixed for that array instance after evaluation. C11/C17 may omit VLA and variably modified type support. C23 requires support for variably modified types but still allows implementations to omit VLA objects with automatic storage duration. Do not assume an arbitrary compiler supports every form.

Strings

A C string is a sequence of characters ending in a null character ('\0'); a char array without a terminator is not a string. String literals have static storage duration, and attempting to modify one is undefined behavior whether or not its physical memory is read-only. Use const char *s = "hello"; for a read-only view, or char buf[] = "hello"; for a writable copy. sizeof buf includes its terminator, whereas strlen(buf) does not.

Key <string.h> Functions

Function Purpose
strlen Length of a string, excluding the terminating \0
strcpy / strncpy Copy a string
strcat / strncat Append a string
strcmp / strncmp Compare strings
strchr / strstr Search for a character / a substring
strtok Tokenize a string by delimiter characters
memcpy / memmove Copy raw bytes (the latter safely handles overlapping regions)
memset Fill a block of memory with a given byte value
memcmp Compare raw bytes

Bounds must match the actual destination capacity. strncpy can leave the destination without a null terminator when the source has at least n characters; it is not a drop-in safe string-copy function. strncat limits appended characters, not the total destination size, and still needs room for the existing string and final null character. snprintf can provide bounded formatted output, but its return value must be checked for errors or truncation. memcpy requires non-overlapping regions; use memmove for overlap. memcmp compares bytes, not general C values.

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 24 / 73

In this chapter

Understanding arrays

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping