C Arrays & Functions
In this page:
Passing Arrays to Functions
When an array decays to a pointer at the function boundary, the function receives only the address of the first element -- the brackets in the parameter list like int arr[] are purely cosmetic and behave identically to int *arr.
Example: Passing Arrays to Functions
#include <stdio.h>
void printFirst(int arr[]) {
printf("%d", arr[0]);
}
int main() {
int nums[3] = {10, 20, 30};
printFirst(nums);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Passing Array Size
This is one of C's most-cited design quirks: sizeof(arr) inside the calling function returns the full array size, but sizeof(arr) inside the called function returns the size of a pointer (8 bytes on most 64-bit systems), so the size must always be passed explicitly.
Example: Passing Array Size
#include <stdio.h>
void printAll(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int nums[3] = {10, 20, 30};
printAll(nums, 3);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying Arrays inside Functions
This pass-by-reference-like behavior is different from how C treats other variable types -- passing an int by value protects the original from changes, but arrays are always effectively passed by reference because only their address is copied.
Example: Modifying Arrays inside Functions
#include <stdio.h>
void doubleValues(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
int main() {
int nums[3] = {1, 2, 3};
doubleValues(nums, 3);
printf("%d %d %d", nums[0], nums[1], nums[2]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Passing Multi-dimensional Arrays
The compiler needs the column count to compute how far to jump in memory between rows (row_size * sizeof(element)), so while arr[][5] is valid as a parameter, arr[][] alone is not enough information for the compiler to index correctly.
Example: Passing Multi-dimensional Arrays
#include <stdio.h>
void printGrid(int arr[][2], int rows) {
for (int i = 0; i < rows; i++) {
printf("%d %d ", arr[i][0], arr[i][1]);
}
}
int main() {
int grid[2][2] = {{1, 2}, {3, 4}};
printGrid(grid, 2);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Returning Arrays Safely
Declaring the array static inside the function keeps it alive after the function returns, unlike a normal local array which is deallocated from the stack -- the tradeoff is that a static array is shared across all calls to that function, which can cause bugs if you're not careful.
Example: Returning Arrays Safely
#include <stdio.h>
int* getArray() {
static int arr[3] = {1, 2, 3};
return arr;
}
int main() {
int *result = getArray();
printf("%d", result[0]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: