Table of contents
1.
Introduction 
2.
How Arrays are Passed in C?
3.
Methods to declare a function that receives an array as an argument
3.1.
First Way – The receiving parameter of the array may itself be declared as an array, as shown below:
3.1.1.
Syntax:-
3.1.2.
Implementation in C
3.2.
C
3.3.
Second Way- The receiving parameters may be declared as an unsized array, as shown below:
3.3.1.
Syntax:-
3.3.2.
Implementation in C
3.4.
C
3.5.
Third Way- The receiving parameters can be declared as a pointer, as shown below:
3.5.1.
Syntax:-
3.5.2.
Implementation in C
3.6.
C
4.
C language passing an array to function example
4.1.
Example 1: Checking Size After Passing Array as Parameter
4.2.
C++
4.3.
Example 2: Printing Array from the Function
4.4.
C++
4.5.
Example 3: Printing Array of Characters (String) using Function
4.6.
C++
5.
C function to sort the array
5.1.
Implementation in C
5.2.
C
6.
Returning array from the function
6.1.
Implementation in C
6.2.
C
7.
Pass Individual Array Elements
7.1.
Implementation in C
7.2.
C
8.
Pass Multidimensional Arrays to a Function
8.1.
Approach 1: Using Array Dimensions
8.1.1.
Implementation in C
8.2.
C
8.3.
Approach 2: Using a Pointer to an Array
8.3.1.
Implementation in C
8.4.
C
9.
Example Demonstrating Passing Array as Reference
9.1.
Implementation in C
10.
C
11.
Advantages of Passing Arrays to Function in C
12.
Disadvantages of Passing Arrays to Function in C
13.
Frequently Asked Questions
13.1.
What happens when you pass an array to a function in C?
13.2.
Why are arrays always passed by reference in C?
13.3.
What are the rules that govern the passing of arrays to function?
13.4.
How do you pass an array to a function by address?
14.
Conclusion
Last Updated: Jul 3, 2024
Easy

Passing Arrays to Function in C

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

In functions, we’ve covered the two different types of invoking (or calling) – Call By Value (or Pass by value) and Call By Reference (or Pass by reference). If you are already familiar with these methods, you may proceed further.

Passing Arrays to Function in C

Passing arrays to functions in C is tricky and interesting. Wanna know how? Let’s get started with Passing Arrays to functions in C.

How Arrays are Passed in C?

An array is a useful tool for grouping and storing comparable data. An array can be passed to C functions using pointers by supplying a reference to the array's base address, and a multidimensional array can also be passed to C methods. Arrays can be returned from functions using pointers by transmitting the array's base address or by establishing a user-defined data type, and this pointer can be used to retrieve array items.

Also see, Ensemble Learning

Methods to declare a function that receives an array as an argument

First WayThe receiving parameter of the array may itself be declared as an array, as shown below:

Syntax:-

return_type function(type arrayname[SIZE])

 

Implementation in C

  • C

C

// Program To find the array sum using function

#include<stdio.h>

int add(int array[5]) { //Declaration with size
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += array[i];
}
return sum;
}
int main() {
int arr[5] = {
2,
3,
4,
5,
6
};
printf("Array sum is %d\n", add(arr)); // For passing array, only its name is passed as argument
return 0;
}
You can also try this code with Online C Compiler
Run Code

OUTPUT

Array sum is 20

Second Way- The receiving parameters may be declared as an unsized array, as shown below:

Syntax:-

return_type function(type arrayname[ ])

 

Implementation in C

  • C

C

// Program to find the minimum element
#include<stdio.h>

int findMin(int arr[], int size) { // Receiving array base address and size
int min = arr[0];
for (int i = 1; i < size; i++) {
if (min > arr[i]) {
min = arr[i];
}
}
return min;
}
int main() {
int arr[5] = {
76,
89,
67,
23,
24
};
printf("The minimum element is %d\n ", findMin(arr, 5)); // Passing array with size
return 0;
}
You can also try this code with Online C Compiler
Run Code

OUTPUT

The minimum element is  23

Third Way- The receiving parameters can be declared as a pointer, as shown below:

Syntax:-

return_type function(type *arrayname) {}

 

Implementation in C

  • C

C

//Program to reverse the array using function
#include <stdio.h>

void reverseArray(int * arr, int start, int end) //Receiving parameter declared as pointer
{
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void printArray(int * arr, int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);

printf("\n");

}
int main() {
int arr[] = {
1,
2,
3,
4,
5,
6
};

int n = sizeof(arr) / sizeof(arr[0]); // calculating size of the array

printArray(arr, n); // To print original array

reverseArray(arr, 0, n - 1); // Calling the function with array name, starting point and ending point

printf("Reversed array is\n");

printArray(arr, n); // To print the Reversed array

return 0;
}
You can also try this code with Online C Compiler
Run Code

OUTPUT

1 2 3 4 5 6

Reversed array is

6 5 4 3 2 1

C language passing an array to function example

Example 1: Checking Size After Passing Array as Parameter

 

Output

Size of array in mai
  • C++

C++

#include <iostream>
using namespace std;

void printArraySize(int arr[]) {
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Size of array inside function: " << size << endl;
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Size of array in main function: " << size << endl;

printArraySize(arr);

return 0;
}
You can also try this code with Online C++ Compiler
Run Code
n function: 5
Size of array inside function: 2

 

 

Explanation: In this example, the function printArraySize() is created to print the size of the array passed as a parameter. However, the size calculated inside the function will not be correct as arrays decay into pointers when passed as function arguments. Hence, the size inside the function will not be the same as in the main function.

Example 2: Printing Array from the Function

  • C++

C++

#include <iostream>
using namespace std;

void printArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);

cout << "Array elements: ";
printArray(arr, size);

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Array elements: 1 2 3 4 5 

 

Explanation: In this example, the function printArray() takes the array and its size as parameters. It then iterates through the array elements and prints them. This approach ensures that the array is printed correctly from within the function.

Example 3: Printing Array of Characters (String) using Function

  • C++

C++

#include <iostream>
using namespace std;

void printString(char str[]) {
int i = 0;
while (str[i] != '\0') {
cout << str[i];
++i;
}
cout << endl;
}

int main() {
char str[] = "Hello, World!";

cout << "String: ";
printString(str);

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

String: Hello, World!

 

 

Explanation: In this example, the function printString() takes a character array (string) as a parameter. It then iterates through the characters until it encounters the null character ('\0') indicating the end of the string, and prints each character. This function allows printing strings without knowing their length in advance.

C function to sort the array

In this section, we will create a function in C that will sort the array of elements (integers). In this function, we will implement the Bubble Sort Algorithm. We will compare adjacent elements for the right comparison and will swap them if they are not present in the right place. Also, there is a main function where we will call this Sort function, and we will print the array in this main function.

Implementation in C

  • C

C

#include<stdio.h>
void Sort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
// Last i elements are already in place
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

int main() {
int arr[] = {10, 6, 2, 1, 0, 11, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Before sorting, array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
Sort(arr, n);
printf("\nAfter Sorting array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
You can also try this code with Online C Compiler
Run Code

OUTPUT

Before sorting, array: 10 6 2 1 0 11 5
After Sorting array: 0 1 2 5 6 10 11

Returning array from the function

In this section, we will create a ‘create’ function in C, where we will create a dynamic array of the given size in the argument, and we will assign the values of i * 2 to each element in the array. lastly, we will return this dynamic array. We will also create the main function where we will ‘create’ function and print the elements of the dynamic array.

Implementation in C

  • C

C

#include <stdio.h>
#include <stdlib.h>

int* createArray(int size) {
int* arr = (int*)malloc(size * sizeof(int));
for (int i = 0; i < size; i++)
arr[i] = i * 2;
return arr;
}

int main() {
int size = 5;
int* returnedArray = createArray(size);

printf("Returned array: ");
for (int i = 0; i < size; i++)
printf("%d ", returnedArray[i]);

return 0;
}
You can also try this code with Online C Compiler
Run Code

OUTPUT

Returned array: 0 2 4 6 8

Pass Individual Array Elements

In C, you can pass individual array elements to a function by specifying the array and the index of the desired element as function arguments. Here's an example:

Implementation in C

  • C

C

#include <stdio.h>

// Function that takes an array and an index as parameters
void processElement(int arr[], int index) {
printf("Element at index %d is: %d\n", index, arr[index]);
}

int main() {
int myArray[] = {10, 20, 30, 40, 50};

// Call the function with individual array elements
// Passes the element at index 2
processElement(myArray, 2);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Element at index 2 is: 30

 

Explanation: In this example, the processElement function takes an array arr and an index index as parameters. The function then prints the element at the specified index. In the main function, the processElement function is called with the myArray array and the index 2.

Pass Multidimensional Arrays to a Function

In C, you can pass multidimensional arrays to a function by specifying the array dimensions or using a pointer to an array. Here are examples demonstrating both approaches:

Approach 1: Using Array Dimensions

Implementation in C

  • C

C

#include <stdio.h>

// Function that takes a 2D array with known dimensions
void processArray(int rows, int cols, int arr[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}

int main() {
int myArray[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

// Call the function with the 2D array
processArray(3, 4, myArray);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

1 2 3 4 
5 6 7 8 
9 10 11 12 

 

Approach 2: Using a Pointer to an Array

Implementation in C

  • C

C

#include <stdio.h>

// Function that takes a pointer to a 2D array
void processArray(int rows, int cols, int (*arr)[cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}

int main() {
int myArray[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

// Call the function with a pointer to the 2D array
processArray(3, 4, myArray);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

1 2 3 4 
5 6 7 8 
9 10 11 12 

Example Demonstrating Passing Array as Reference


In C, arrays are typically passed by reference by default since they decay into pointers when passed to functions. Here's an example demonstrating passing an array as a reference:

Implementation in C

  • C

C

#include <stdio.h>

// Function that takes an array as reference
void modifyArray(int arr[], int size) {
// Modify the array elements
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}

int main() {
int myArray[] = {1, 2, 3, 4, 5};
int size = sizeof(myArray) / sizeof(myArray[0]);

// Call the function, passing the array by reference
modifyArray(myArray, size);

// Print the modified array
printf("Modified Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", myArray[i]);
}

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Modified Array: 2 4 6 8 10

 

Explanation: In this example, the modifyArray function takes an array arr and its size as parameters. Since arrays decay into pointers, this is effectively passing the array by reference. The function then modifies each element of the array by doubling its value.

When the modifyArray function is called from the main function with the myArray, it modifies the array in place.

Advantages of Passing Arrays to Function in C

The advantages of passing arrays to function in C are:

  • Memory Efficiency: Passing arrays to functions in C allows for more memory-efficient programs, as it avoids duplicating the entire array's data. Only the array's address is passed, reducing memory consumption.
  • Modularity and Reusability: Function parameters provide a modular approach, enabling code reuse. A function designed to operate on arrays can be easily employed with various arrays in different parts of the program.
  • Enhanced Readability: Array parameters in function signatures enhance code readability by clearly indicating the purpose and data type of the input. This promotes a better understanding of the function's intended usage.
  • Flexible Array Sizes: Functions can handle arrays of variable sizes by specifying the array size using parameters. This flexibility allows the same function to work with arrays of different lengths.
  • Easier Maintenance: Changes to array manipulation logic can be made within the function, simplifying maintenance. Modifications made in the function affect all instances where the function is called, promoting code consistency.

Disadvantages of Passing Arrays to Function in C

The disadvantages of passing arrays to function in C are:

  • No Bounds Checking: C does not inherently perform bounds checking on array accesses. Passing arrays to functions without proper size management may lead to buffer overflows, resulting in unpredictable behavior.
  • Limited Information Passing: Arrays lose their size information when passed to functions. Developers must either use sentinel values or pass the array size explicitly to avoid ambiguities.
  • Potential for Pointer Arithmetic Errors: In C, array names can decay into pointers, introducing the potential for pointer arithmetic errors. Developers must handle pointers carefully to avoid unintended side effects.
  • Inability to Return Entire Arrays: C functions cannot return entire arrays directly. Developers often use pointers or dynamic memory allocation to work around this limitation, introducing complexity.
  • Passing Large Arrays by Value: Passing large arrays by value can lead to inefficient memory usage and performance issues. In such cases, passing a pointer to the array may be more suitable.

Frequently Asked Questions

What happens when you pass an array to a function in C?

When you pass an array to a function in C, the reference of that array is passed by which we can modify and access the elements of the array. Here, reference means the address of the first element of the array.

Why are arrays always passed by reference in C?

Arrays are passed by reference in C because you can access and modify the elements in the array, and the changes will be made in the original array because you are passing the memory address.

What are the rules that govern the passing of arrays to function?

The rules for passing arrays to functions include determining whether the array is passed by reference or value, matching the array's dimension and type with the function argument, and specifically addressing array size and length if necessary. Furthermore, some languages use pointers or references to effectively pass arrays.

How do you pass an array to a function by address?

To pass an array to a function by address in C or C++, use a pointer as the function parameter. Declare the function with a pointer type parameter, which allows modification of the original array in the calling function.

Conclusion

To conclude, we’ve discussed the three ways of passing arrays to functions in C. The key point is that, in every way, an array is passed as the reference. The compiler automatically converts the array into the pointer array. Also, If an individual element of an array is passed to a function, it is passed according to its underlying data type.

Tadda, you made it here; kudos for your efforts.

Recommended Readings:


Don’t stop here, Ninja, get yourself enrolled in a free guided path and practice the coding questions on code studio. 

Happy Learning Ninja!

Live masterclass