Introduction
Passing arrays to functions in C is a fundamental concept for working with collections of data. Unlike basic data types, arrays are not passed by value but by reference, meaning the function receives a pointer to the first element. This allows functions to modify the original array and work efficiently with large datasets.
Key Concepts
Array Parameter: Function parameter that receives array address Pass by Reference: Arrays automatically passed as pointers Array Decay: Array name converts to pointer when passed Size Parameter: Separate parameter needed for array size Pointer Arithmetic: Used to access array elements in functions
Basic Array Passing
1. One-Dimensional Array Passing
#include <stdio.h>
// Method 1: Array notation
void displayArray1(int arr[], int size) {
printf("Array elements (method 1): ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Method 2: Pointer notation
void displayArray2(int *arr, int size) {
printf("Array elements (method 2): ");
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
}
// Method 3: Fixed size array (less flexible)
void displayArray3(int arr[5]) {
printf("Array elements (method 3): ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to modify array elements
void doubleArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
}
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Passing Arrays to Functions:\n");
// Display original array
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Different methods of passing arrays
displayArray1(numbers, size);
displayArray2(numbers, size);
displayArray3(numbers);
// Modify array through function
doubleArray(numbers, size);
printf("After doubling: ");
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
2. Array Operations Functions
#include <stdio.h>
// Find sum of array elements
int arraySum(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
// Find maximum element
int findMax(int arr[], int size) {
if (size <= 0) return -1;
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// Count occurrences of a value
int countOccurrences(int arr[], int size, int target) {
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
count++;
}
}
return count;
}
// Reverse array elements
void reverseArray(int arr[], int size) {
for (int i = 0; i < size / 2; i++) {
int temp = arr[i];
arr[i] = arr[size - 1 - i];
arr[size - 1 - i] = temp;
}
}
// Search for element (linear search)
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
int main() {
int data[] = {10, 25, 30, 25, 40, 15, 25};
int size = sizeof(data) / sizeof(data[0]);
printf("Array Operations:\n");
printf("Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", data[i]);
}
printf("\n");
// Perform operations
printf("Sum: %d\n", arraySum(data, size));
printf("Maximum: %d\n", findMax(data, size));
printf("Count of 25: %d\n", countOccurrences(data, size, 25));
int index = linearSearch(data, size, 30);
if (index != -1) {
printf("30 found at index: %d\n", index);
}
// Reverse and display
reverseArray(data, size);
printf("Reversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", data[i]);
}
printf("\n");
return 0;
}
3. Character Array (String) Passing
#include <stdio.h>
#include <string.h>
// Display string
void displayString(char str[]) {
printf("String: %s\n", str);
}
// Calculate string length manually
int stringLength(char str[]) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
// Convert to uppercase
void toUpperCase(char str[]) {
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32;
}
}
}
// Count vowels in string
int countVowels(char str[]) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
char ch = str[i];
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
}
}
return count;
}
// Reverse string
void reverseString(char str[]) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - 1 - i];
str[length - 1 - i] = temp;
}
}
int main() {
char message[] = "Hello World";
printf("String Array Passing:\n");
displayString(message);
printf("Length: %d\n", stringLength(message));
printf("Vowels: %d\n", countVowels(message));
// Create copy for uppercase conversion
char upperMsg[50];
strcpy(upperMsg, message);
toUpperCase(upperMsg);
printf("Uppercase: %s\n", upperMsg);
// Create copy for reverse
char revMsg[50];
strcpy(revMsg, message);
reverseString(revMsg);
printf("Reversed: %s\n", revMsg);
return 0;
}
Two-Dimensional Array Passing
1. Passing 2D Arrays
#include <stdio.h>
// Method 1: Specify column size
void display2DArray1(int arr[][3], int rows) {
printf("2D Array (method 1):\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
// Method 2: Using pointer notation
void display2DArray2(int (*arr)[3], int rows) {
printf("2D Array (method 2):\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
// Find sum of all elements
int sum2DArray(int arr[][3], int rows) {
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
sum += arr[i][j];
}
}
return sum;
}
// Find maximum element
int findMax2D(int arr[][3], int rows) {
int max = arr[0][0];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
}
return max;
}
// Transpose matrix (for square matrices)
void transpose(int arr[][3], int size) {
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("2D Array Passing:\n");
display2DArray1(matrix, 3);
display2DArray2(matrix, 3);
printf("Sum of all elements: %d\n", sum2DArray(matrix, 3));
printf("Maximum element: %d\n", findMax2D(matrix, 3));
// Transpose and display
printf("\nAfter transpose:\n");
transpose(matrix, 3);
display2DArray1(matrix, 3);
return 0;
}
2. Dynamic 2D Array Passing
#include <stdio.h>
#include <stdlib.h>
// Function to allocate 2D array
int** allocate2DArray(int rows, int cols) {
int **arr = malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
arr[i] = malloc(cols * sizeof(int));
}
return arr;
}
// Function to free 2D array
void free2DArray(int **arr, int rows) {
for (int i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);
}
// Fill 2D array with values
void fill2DArray(int **arr, int rows, int cols) {
int value = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = value++;
}
}
}
// Display dynamic 2D array
void displayDynamic2D(int **arr, int rows, int cols) {
printf("Dynamic 2D Array:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%3d ", arr[i][j]);
}
printf("\n");
}
}
int main() {
int rows = 4, cols = 3;
printf("Dynamic 2D Array Passing:\n");
// Allocate and fill array
int **dynamicArray = allocate2DArray(rows, cols);
fill2DArray(dynamicArray, rows, cols);
displayDynamic2D(dynamicArray, rows, cols);
// Clean up memory
free2DArray(dynamicArray, rows);
return 0;
}
Array Sorting Functions
Sorting Algorithms
#include <stdio.h>
// Bubble sort
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Selection sort
void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap minimum element with first element
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
// Insertion sort
void insertionSort(int arr[], int size) {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
// Move elements greater than key one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
// Utility function to display array
void printArray(int arr[], int size, char* message) {
printf("%s", message);
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to copy array
void copyArray(int source[], int dest[], int size) {
for (int i = 0; i < size; i++) {
dest[i] = source[i];
}
}
int main() {
int original[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(original) / sizeof(original[0]);
printf("Array Sorting Functions:\n");
printArray(original, size, "Original array: ");
// Test bubble sort
int arr1[7];
copyArray(original, arr1, size);
bubbleSort(arr1, size);
printArray(arr1, size, "Bubble sort: ");
// Test selection sort
int arr2[7];
copyArray(original, arr2, size);
selectionSort(arr2, size);
printArray(arr2, size, "Selection sort: ");
// Test insertion sort
int arr3[7];
copyArray(original, arr3, size);
insertionSort(arr3, size);
printArray(arr3, size, "Insertion sort: ");
return 0;
}
Advanced Array Functions
Binary Search and Utilities
#include <stdio.h>
// Binary search (array must be sorted)
int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Not found
}
// Merge two sorted arrays
void mergeArrays(int arr1[], int size1, int arr2[], int size2, int result[]) {
int i = 0, j = 0, k = 0;
while (i < size1 && j < size2) {
if (arr1[i] <= arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
// Copy remaining elements
while (i < size1) {
result[k++] = arr1[i++];
}
while (j < size2) {
result[k++] = arr2[j++];
}
}
// Remove duplicates from sorted array
int removeDuplicates(int arr[], int size) {
if (size == 0) return 0;
int unique = 0;
for (int i = 1; i < size; i++) {
if (arr[i] != arr[unique]) {
unique++;
arr[unique] = arr[i];
}
}
return unique + 1; // Return new size
}
// Rotate array to the right
void rotateRight(int arr[], int size, int positions) {
positions = positions % size; // Handle positions > size
// Reverse entire array
for (int i = 0; i < size / 2; i++) {
int temp = arr[i];
arr[i] = arr[size - 1 - i];
arr[size - 1 - i] = temp;
}
// Reverse first positions elements
for (int i = 0; i < positions / 2; i++) {
int temp = arr[i];
arr[i] = arr[positions - 1 - i];
arr[positions - 1 - i] = temp;
}
// Reverse remaining elements
for (int i = positions; i < (size + positions) / 2; i++) {
int temp = arr[i];
arr[i] = arr[size - 1 - (i - positions)];
arr[size - 1 - (i - positions)] = temp;
}
}
int main() {
printf("Advanced Array Functions:\n");
// Binary search example
int sorted[] = {1, 3, 5, 7, 9, 11, 13, 15};
int size = sizeof(sorted) / sizeof(sorted[0]);
int target = 7;
int index = binarySearch(sorted, size, target);
printf("Binary search for %d: %s\n", target,
index != -1 ? "Found" : "Not found");
// Merge arrays example
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 4, 6, 8};
int merged[8];
mergeArrays(arr1, 4, arr2, 4, merged);
printf("Merged array: ");
for (int i = 0; i < 8; i++) {
printf("%d ", merged[i]);
}
printf("\n");
// Remove duplicates example
int withDups[] = {1, 1, 2, 2, 3, 4, 4, 5};
int newSize = removeDuplicates(withDups, 8);
printf("After removing duplicates: ");
for (int i = 0; i < newSize; i++) {
printf("%d ", withDups[i]);
}
printf("\n");
// Rotate array example
int rotate[] = {1, 2, 3, 4, 5};
rotateRight(rotate, 5, 2);
printf("After rotating right by 2: ");
for (int i = 0; i < 5; i++) {
printf("%d ", rotate[i]);
}
printf("\n");
return 0;
}
Important Points
- Arrays passed by reference automatically in C
- Size parameter required since array size not passed
- Array name is pointer to first element
- Modifications affect original array
- *Can use array[i] or (arr+i) notation
- 2D arrays need column size specified in function parameter
- Dynamic arrays require explicit memory management
- String arrays are character arrays with null terminator
Best Practices
- Always pass size parameter with array
- Validate array pointers before use
- Use const for read-only array parameters
- Document array requirements in function comments
- Handle empty arrays gracefully
- Use meaningful parameter names for clarity
- Consider bounds checking for safety
- Free dynamically allocated arrays properly
Summary
Passing arrays to functions in C involves passing pointers to the first element, allowing functions to access and modify original array data. Array size must be passed separately as arrays don’t carry size information. Both one-dimensional and multi-dimensional arrays can be passed, with different syntax requirements. Understanding array passing is crucial for writing efficient functions that work with collections of data.
Part of BCA Programming with C Course (UGCOA22J201)