In C programming, we can pass arrays to functions just like any other variable.
When an array is passed to a function, it's actually passed by reference, which means the function receives a pointer to the first element of the array.
This allows the function to access and modify the original array.
Here's how we can pass arrays to functions in C:
#include <stdio.h> // Function to print elements of an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int numbers[] = {1, 2, 3, 4, 5}; // sizeof(numbers) = 4 bits * 5 element = 20; // sizeof(numbers[0]) = 4 bits; // exact size of elements in array then = 20 bits / 4 bits = 5 elements; int size = sizeof(numbers) / sizeof(numbers[0]); // Passing the array to the function printArray(numbers, size); return 0; }
#include <stdio.h> // Function to print elements of a two-dimensional array void printMatrix(int matrix[][3], int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } } int main() { int matrix[][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int rows = sizeof(matrix) / sizeof(matrix[0]); int cols = sizeof(matrix[0]) / sizeof(matrix[0][0]); // Passing the array to the function printMatrix(matrix, rows, cols); return 0; }
C does not allow directly returning arrays from functions.
However, we can return a pointer to the array or dynamically allocate memory inside the function and return the pointer to the allocated memory.
Here's an example of returning a pointer to the array:
#include <stdio.h> // Function to create and return an array int *createArray(int size) { static int arr[100]; // Static to avoid local variable issue for (int i = 0; i < size; i++) { arr[i] = i + 1; } return arr; } int main() { int size = 5; int *result = createArray(size); for (int i = 0; i < size; i++) { printf("%d ", result[i]); } printf("\n"); return 0; }
When passing arrays to functions, we don't need to specify the size of the array explicitly. However, we need to pass the size of the array as a separate parameter.
In C, arrays are always passed by reference, so any modifications made to the array inside the function will affect the original array.
Be cautious about array bounds to avoid accessing out-of-bounds memory, which can lead to undefined behaviour.