03. Passing Arrays to Functions & Pointer Decay
🟡 Difficulty: Intermediate | Array Decay to Pointer, Size Loss & Const Guarding
📖 Definition
In C, when an array name is passed as an argument to a function, it automatically decays into a pointer to its first element (&arr[0]). The function receives a pointer copy, NOT a full copy of the array elements. Consequently, sizeof(arr) inside a function evaluates to the byte size of a pointer (8 bytes on 64-bit systems), requiring callers to pass array size explicitly as a separate parameter.
🎯 Why It Is Used
- Zero Copy Performance: Passing a pointer to an array of 1,000,000 integers takes constant O(1) time and pushes only an 8-byte pointer onto the stack.
- In-Place Array Mutation: Functions can modify array elements directly in the caller's memory frame.
- Read-Only Guarding (
const): Prefixing array parameters withconstprevents unwanted element mutations.
⚙️ How It Works: The Size Loss Problem
In the caller function, sizeof(arr) returns the full allocated byte size (e.g. 5 * 4 = 20 bytes). Inside the receiving function, the parameter int arr[] is silently rewritten by the compiler to int *arr. Therefore, calling sizeof(arr) / sizeof(arr[0]) inside the function evaluates to 8 / 4 = 2, which is WRONG!
📝 Syntax
// 1. Equivalent Function Prototypes (Compiler treats both identically as int *arr)
void process_elements(int arr[], size_t size);
void process_elements(int *arr, size_t size);
// 2. Read-Only Array Parameter (Compiler enforces immutability)
void print_elements(const int arr[], size_t size);
🔀 Array Parameter Syntax Forms
| Syntax Form | How Compiler Interprets It | Can Modify Array? |
|---|---|---|
void fn(int arr[], size_t n) | void fn(int *arr, size_t n) | ✅ Yes |
void fn(int arr[100], size_t n) | void fn(int *arr, size_t n) (Size 100 IGNORED!) | ✅ Yes |
void fn(const int arr[], size_t n) | void fn(const int *arr, size_t n) | ❌ No (Compiler Guarded) |
🌱 Beginner Example: Demonstrating Array Decay & Size Loss
#include <stdio.h>
void print_array_size_info(int arr[], size_t caller_size) {
printf("Inside Function : sizeof(arr) = %zu bytes (Pointer size!)\n", sizeof(arr));
printf("Explicit Passed Size: %zu elements\n", caller_size);
}
int main(void) {
int numbers[5] = {10, 20, 30, 40, 50};
size_t count = sizeof(numbers) / sizeof(numbers[0]);
printf("Inside main() : sizeof(numbers) = %zu bytes\n", sizeof(numbers));
print_array_size_info(numbers, count);
return 0;
}
🌼 Intermediate Example: Read-Only Print vs In-Place Scale
#include <stdio.h>
// Read-only array traversal
void print_vector(const double vec[], size_t len) {
printf("[ ");
for (size_t i = 0; i < len; i++) {
printf("%.1lf ", vec[i]);
}
printf("]\n");
}
// In-place mutation
void scale_vector(double vec[], size_t len, double factor) {
for (size_t i = 0; i < len; i++) {
vec[i] *= factor;
}
}
int main(void) {
double data[] = {1.5, 2.5, 3.5};
size_t len = sizeof(data) / sizeof(data[0]);
printf("Original Vector : ");
print_vector(data, len);
scale_vector(data, len, 2.0);
printf("Scaled Vector x2: ");
print_vector(data, len);
return 0;
}
🌲 Advanced Example: Passing 2D Matrices to Functions
#include <stdio.h>
#define COLS 3
// Column dimension COLS is MANDATORY in parameter definition!
void print_matrix_2d(const int mat[][COLS], size_t rows) {
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < COLS; c++) {
printf("%3d ", mat[r][c]);
}
printf("\n");
}
}
int main(void) {
int matrix[2][COLS] = {
{10, 20, 30},
{40, 50, 60}
};
printf("=== 2D Matrix Output via Function ===\n");
print_matrix_2d(matrix, 2);
return 0;
}
🔍 Line-by-Line Explanation
void print_array_size_info(int arr[], size_t caller_size): Demonstrates parameter decay wherearr[]is treated asint *arr.void print_vector(const double vec[], ...): Usesconstmodifier so caller knows vector data will not be modified.void print_matrix_2d(const int mat[][COLS], ...): Declares 2D parameter requiring fixed column width for correct address offset calculation.
💻 Expected Terminal Output
Inside main() : sizeof(numbers) = 20 bytes
Inside Function : sizeof(arr) = 8 bytes (Pointer size!)
Explicit Passed Size: 5 elements
Original Vector : [ 1.5 2.5 3.5 ]
Scaled Vector x2: [ 3.0 5.0 7.0 ]
=== 2D Matrix Output via Function ===
10 20 30
40 50 60
⚠️ Common Mistakes & Pitfalls
- Calculating Array Size Inside Function: Writing
size = sizeof(arr)/sizeof(arr[0])inside a receiving function yields incorrect results due to pointer decay. - Assuming Brackets Enforce Fixed Lengths: Writing
void fn(int arr[10])does NOT restrict argument size to 10; the compiler ignores 10 and degrades parameter toint *arr.
📌 Important Rules & Limitations
- Arrays decay to pointers when passed to functions.
- Always pass the array length as an additional explicit parameter.
- Use
constfor read-only array parameters.
🌐 Multilingual Explanation: English
When an array is passed to a function, it decays to a pointer. Always pass the array size explicitly as a separate parameter, and use const for read-only functions.
🌐 Multilingual Explanation: Hindi (Roman Script)
Function mein array bhejte hi wo pointer mein decay ho jata hai. Iss wajah se function ke andar array ka exact size alag se parameter ke roop mein bhejna zaroori hai.
🌐 Multilingual Explanation: Marathi (Roman Script)
Function madhye array pass kelya nantar to pointer madhye convert (decay) hoto. Mhanun array cha size veglaya parameter dwara pass kara lagto.
❓ Practice Questions
- Why does
sizeof(arr)inside a function return 8 bytes on a 64-bit machine regardless of array length? - How does placing
constbefore an array parameter protect data? - What happens if you declare a function parameter as
void fn(int arr[50])and pass a 5-element array to it?
🚀 Practical Coding Challenge
Write a C program named array_stats.c with a function double compute_average(const int arr[], size_t size) that calculates and returns the arithmetic mean of an array without modifying its elements.
🧭 Navigation & Breadcrumbs
← Previous: 02. 2D Matrices | Module 09 Guide | Next: 04. Variable-Length Arrays →