Arrays as parameters in C: solved exercise
Arrays as parameters in C: solved exercise
If you searched for a solved arrays as parameters exercise in C, here is the fundamental pattern: in C, arrays are passed to functions as a pointer to the first element, which means the function can modify the original array and the size must be passed separately.
This behavior — called array-to-pointer decay — is one of the first stumbling blocks for developers coming from Java or Python, where arrays carry their own size.
Problem statement
Write three functions:
fill(arr, n): fills the array with values0, 2, 4, …, 2*(n-1).sum(arr, n): returns the sum of all elements (without modifying the array).print_array(arr, n): prints all elements separated by spaces.
Demonstrate that modifications made by fill are visible in main.
C solution
Expected output
Common mistakes
- Trying to get the array size inside the function using
sizeof(arr): it returns the size of the pointer (8 bytes on 64-bit), not the array. Size must always be passed as a parameter. - Forgetting
constin functions that only read the array: the compiler cannot optimize or detect accidental modifications. - Passing
&vinstead ofv:&vis a pointer to array (int (*)[5]), a different type from what the function expects. - Confusing stack arrays (
int v[5]) with dynamic arrays (malloc): both are passed as a pointer, but their lifetimes differ.
Practical use
Passing arrays to functions is the foundation of sorting, searching, and transformation algorithms in C. Separating logic into functions with const allows the compiler to apply optimizations and helps the programmer reason about side effects.
Recommended next exercise
- Arrays in C: solved exercises
- Pointers in C: solved exercises
- Functions in C: solved exercises
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why doesn’t sizeof(arr) give the array size inside the function?
Because when an array is passed to a function, it decays to a pointer to its first element. The function receives only the memory address, not the length. sizeof on a pointer returns the pointer size (4 or 8 bytes depending on the architecture).
What is the difference between int arr[] and int *arr as a function parameter?
None in practice: both declarations are equivalent in the context of function parameters. C treats them identically. int arr[] is preferred for semantic clarity.
How do you pass a two-dimensional array to a function?
For matrices, you must specify the number of columns: void f(int mat[][COLS], int rows). The column count must be a compile-time constant, or use pointer-to-pointer for fully dynamic dimensions.