Curious Minds

Clear answers to science and history questions

Why Do Arrays Decay to Pointers in C? Core Reasons and Details

· 6 min read · Science

Arrays decay to pointers in C because when an array expression is used in most contexts, the compiler implicitly converts it to a pointer to its first element, a rule defined by the language standard to enable efficient pointer-based access and compatibility with function parameters.

Background

In C, arrays and pointers are closely related but distinct types. An array type, such as int arr[10], represents a contiguous block of memory for 10 integers. However, when the array name appears in an expression, it is often converted (or "decays") to a pointer to its first element unless it is the operand of the sizeof operator, the & operator, or a string literal used to initialize another array. This behavior stems from early design decisions in C to make arrays work seamlessly with pointers, reflecting the language’s low-level nature and desire for efficiency. The decay rule avoids unnecessary copying of entire arrays and allows functions to accept pointers instead of requiring array parameters, which would be impractical due to C’s lack of true array parameters.

How It Works

Array decay occurs automatically during expression evaluation. When the compiler encounters an array identifier in a context that expects a pointer (such as an assignment, function argument, or arithmetic operation), it generates the address of the first element. For example, in int *p = arr;, the array arr decays to &arr[0]. Similarly, when passing an array to a function like func(arr), the function receives a pointer to the first element, not the array itself. This conversion happens at compile time and does not involve runtime overhead. The decay applies only to lvalue arrays; rvalue arrays (such as those returned from functions, though C does not allow returning arrays directly) do not decay in the same way because they are not lvalues.

Common Problems

One frequent issue arises when programmers mistakenly believe that array decay preserves size information. For instance, inside a function, a parameter declared as int arr[] is actually adjusted by the compiler to int *arr, meaning sizeof(arr) inside the function returns the size of a pointer, not the array. This leads to bugs when trying to determine array length using sizeof. Another problem occurs with multi-dimensional arrays: only the first dimension decays. In int matrix[5][10], matrix decays to int (*)[10], a pointer to an array of 10 integers, not int**. Misunderstanding this can cause incorrect pointer arithmetic or type errors.

Comparisons

Array decay contrasts with how arrays behave in other languages. In C++, arrays also decay to pointers in most contexts, but C++ introduces references and templates that can preserve array size information (e.g., via std::array or template deduction). In Java, arrays are objects and do not decay; array variables are references to array objects, and their length is accessible via a length field. In C#, similar to Java, arrays are reference types with built-in length properties. C’s decay rule reflects its design as a systems language where direct memory access and minimal abstraction are prioritized over safety or convenience features found in higher-level languages.

Costs

The primary cost of array decay is the loss of size information, which places the burden on the programmer to manage array bounds manually. This can lead to buffer overflows if not handled carefully, a common source of security vulnerabilities in C programs. There is no runtime performance cost associated with the decay itself—it is a compile-time transformation—but the need to manually track sizes often results in additional code for length parameters or sentinel values (like null-terminated strings). Compared to alternatives such as passing a struct containing the array and its size, decay reduces function call overhead by avoiding the copy of aggregate data, though modern compilers often optimize such structs effectively.

Safety

Array decay does not introduce memory safety issues by itself, but it enables unsafe practices if not used with care. Since the decayed pointer carries no bounds information, functions receiving it cannot validate indices without additional parameters. This contributes to risks like out-of-bounds writes, which can corrupt memory or be exploited in attacks. Safe usage requires either passing explicit size parameters, using null-termination conventions (for strings), or adopting safer abstractions like struct wrappers or external libraries. Static analysis tools and compiler flags (e.g., -Wall -Wextra in GCC) can help detect potential misuse, but they cannot eliminate the fundamental limitation imposed by decay.

Alternatives

While array decay is inherent to C’s design, programmers can work around its limitations. One approach is to pass arrays to functions using pointers paired with explicit size parameters: void process(int *data, size_t len). Another is to define a struct that wraps the array and its size, though this involves copying unless passed by pointer. For string handling, relying on null-termination is standard but requires discipline. In modern C, flexible array members in structs allow dynamic sizing while keeping related data together. Some projects use macros or inline functions to encapsulate size-aware operations. However, none of these eliminate decay; they merely compensate for its consequences in specific use cases.

Frequently Asked Questions

Does array decay happen with multi-dimensional arrays?

Yes, but only the first dimension decays. For example, a int arr[3][4] expression converts to a pointer of type int (*)[4], pointing to the first row (an array of 4 integers). The second dimension does not decay because it is part of the array type pointed to by the resulting pointer.

Can I prevent array decay?

You cannot prevent decay in expressions where it is defined by the language, but you can avoid contexts that trigger it. Using the array with sizeof or & inhibits decay—for instance, sizeof(arr) gives the total size in bytes, and &arr yields a pointer to the entire array object (not just its first element).

Why doesn’t sizeof work inside functions on array parameters?

Because array parameters are adjusted to pointers by the compiler. A declaration like void f(int arr[10]) is treated as void f(int *arr), so sizeof(arr) evaluates to the size of a pointer, not the array. To preserve size, pass it explicitly or use a different design.

Is array decay the same as array-to-pointer conversion?

Yes, these terms describe the same implicit conversion defined in the C standard. Whenever an array of type T[N] appears in an expression (except as noted), it is converted to a pointer of type T* pointing to its first element.

Do string literals decay?

Yes, string literals like "hello" are arrays of char (including the null terminator) and decay to char* in most contexts. This is why you can initialize a char* pointer with a string literal. However, attempting to modify the contents of a string literal via such a pointer results in undefined behavior.

Does decay apply to arrays in structs?

No, when an array is a member of a struct, accessing it via the struct (e.g., struct s.arr) does not cause decay because it is not an array expression in a decay context—it is a member access. However, if you use struct s.arr in an expression that expects a pointer (like passing it to a function), then it will decay.

In this article
  1. Background
  2. How It Works
  3. Common Problems
  4. Comparisons
  5. Costs
  6. Safety
  7. Alternatives
  8. Frequently Asked Questions