Arrays and Functions
Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Data Structures #◇Data Types #◇Structured Programming #◇Memory Management
◇Overview
Only the pointer to the first element is passed.
◇Details / Theory
Passing 1D Arrays
Only the pointer to the first element is passed.
Function Syntax:
void myFunction(int arr[], int size); // or int *arr
Example:
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
Personal Note: Always pass the array size to avoid memory errors.
Passing 2D Arrays
All dimensions except the first must be specified.
Function Syntax:
void myFunction(int arr[][COLS], int numRows);
Example:
#define ROWS 2
#define COLS 3
void print2DArray(int arr[][COLS], int numRows) {
for (int r = 0; r < numRows; r++) {
for (int c = 0; c < COLS; c++) {
printf("%d\t", arr[r][c]);
}
printf("\n");
}
}
Personal Note: For more flexibility, use pointers or flatten the array.
◇Common Pitfalls
Forgetting that arrays decay to pointers when passed to functions — the function receives a pointer, not a copy, so modifications affect the original array Not passing the size alongside the array — inside the function, sizeof(arr) returns the pointer size, not the array size For 2D arrays, forgetting to specify all dimensions except the first in the function parameter (e.g., void f(int arr[][COLS], int rows)) Assuming sizeof(arr)/sizeof(arr[0]) works inside functions — it only works in the scope where the array was declared
◇Summary
TL;DR — Pass 1D arrays as
type *arr(ortype arr[]) plus asizeparameter. For 2D arrays, specify all dimensions except the first:type arr[][COLS]. Arrays decay to pointers, so the function modifies the original data. Always pass size explicitly.
◇Links
Related: Source / Reference:
◇References & Navigation
- Previous Topic: ◇Multidimensional Arrays (3D+)
- Next Topic: ◇Arrays and Pointers
- Related Notes: ◇Functions and Programs, ◇Subprograms
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
What is passed to a function when a 1D array is provided as an argument in C?
How should you properly declare a function that takes a 1D array as a parameter?
What happens if a function modifies an array passed to it as an argument?
When passing a 2D array to a function, which dimensions must be specified in the parameter?
Why is it necessary to pass the size of an array alongside it to a function?
What will sizeof(arr) return inside a function where arr is passed as an array parameter?
Which of the following is a valid function parameter declaration for a 2D array?
Why does sizeof(arr)/sizeof(arr[0]) fail to find the array length inside a function?
Which syntax allows for more flexibility when dealing with 2D arrays in functions?
What is a key reason that passing an array does not create a copy?