How to Pass Array as a Parameter to a Function in C

SPONSOR AD

How to Pass Array as a Parameter to a Function in C Language

In this article, we will discuss How to Pass an Array as a Parameter to a Function in C Language with Examples. Please read our previous article discussing Pointer to Structure in C Program. At the end of this article, you will understand the following pointer.

  1. Passing Array as a Parameter to a Function in C Language
  2. Returning an Array From a Method in C Language
  3. Different Mechanisms to Pass an Array to a Function in C
  4. Passing Array and Size
  5. Passing as a Pointer
  6. Passing a Fixed-Size Array
  7. Passing a Multidimensional Array
  8. When to Pass Array as a Parameter to a Function in C?
Passing Array as a Parameter to a Function in C Language:

Let us understand this with an example. Please have a look at the following example. As you can see in the below code, the main function has an array of size 5, and it is also initialized with five elements (2,4,6,8,10). The array’s name is A. Then we call a function, i.e., fun, passing that array A and an integer number that represents the size of the array. The fun function takes two parameters. The first parameter is an array, i.e., B, and for passing an array as a parameter, we need to mention empty brackets [], and we should not give any size. The fun function doesn’t know the size of the array because the array actually belongs to the main function. So, we should also pass the size of the array, and for that, the second parameter, i.e., n, is being used. So, this B is actually a pointer to an array. It is not an array itself. It’s a pointer to an array. We are printing all the array elements within the function using a for loop.

#include <stdio.h>
void fun (int B[], int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf ("%d", B[i]);
    }
}

int main ()
{
   int A[5] = { 2, 4, 6, 8, 10 };
   fun (A, 5);
}
What Parameter Passing Method is Used in this Example?

You must remember that an array is always passed by address, not by the value, both in C and C++. That means the base address of the array A is given to the pointer, i.e., to B. Here, B is just a pointer, and giving a bracket means it is a pointer to an array. The second parameter is n, and if you notice there is no *, then it is not called by address, and if there is no &, then it is not called by reference. That means it is the call-by-value like just a normal variable. So, there are two parameters: one is passed by address, and another is passed by value.

Can we write * instead of []?

Yes, we can. Instead of writing brackets, you can even write ‘*’ there, as shown in the below code. Here, B is an integer pointer that will be pointing to an array.

SPONSOR AD
#include <stdio.h>
void fun (int *B, int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf ("%d", B[i]);
    }
}

int main ()
{
   int A[5] = { 2, 4, 6, 8, 10 };
   fun (A, 5);
}
What is the difference between *B and B[]?

The difference is that *B is an integer pointer that can point to an integer variable as well as it can also point to an integer array. On the other hand, B[] is a pointer that can only point to an integer array and not point to an integer variable.

One more point you need to understand: within the fun function, if you modify the array, it will reflect the same in the main function as the array uses the pass-by address mechanism. Let us understand this with an example.

#include <stdio.h>
void fun (int *B)
{
    B[0] = 20;
    B[2] = 30;
}

int main ()
{
    int A[5] = { 2, 4, 6, 8, 10 };
    fun (A);
    for (int i = 0; i < 5; i++)
    {
        printf ("%d ", A[i]);
    }
}
Returning an Array From a Method in C Language:

The C programming language does not allow the return of an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array’s name without an index.

To understand this, please have a look at the below code. As you can see in the code below, we have a pointer variable *A inside the main function. Then, the main function calls the fun function by passing a value of 5. The fun function, which takes parameter n, will store the incoming value 5, passed by the value mechanism. The fun function also has a pointer variable, i.e., *p, and it allocates an array of size of type integer * 5 in the heap area. We already discussed that the malloc function allocates memory in the heap area. In the heap area, it creates an array with size five and stores the base address of that array in the integer pointer, i.e., *p.

#include <stdio.h>
int* fun(int n)
{
    int *p;
    p = (int *) malloc (n * sizeof (int));
    return (p);
}

int main ()
{
    int *A;
    A = fun (5);
}
How Does it Work?

The program execution starts from the main method. The main method first creates an integer pointer variable. The integer pointer variable can point to normal variables and an array. Then, it calls the function fun() by passing 5 as the value.

The fun function takes a parameter n, and the value 5 will be stored in it. Then, the malloc() function will allocate the memory in the heap, and an array of size 5 will be created inside the heap. The address of that array will be present in p. After allocating the memory in the heap and storing the base address in point variable p. It returns that pointer variable, i.e., the base address of the array whose memory is allocated in the heap.

Inside the main function, the pointer variable, i.e., A, will point to the array created in the heap memory. For a better understanding, please have a look at the below image.

SPONSOR AD

Array as Parameter

Key Points:
  • When an array is passed to a function, what’s actually being passed is the address of its first element. The array itself is not copied, which makes array passing in C efficient in terms of memory usage.
  • The function receives no information about the array size, so this must be managed separately.
  • The modifications to the array inside the function will affect the original array since the array is passed by reference.

Different Mechanisms to Pass an Array to a Function in C

Passing an array to a function in C can be done in a few different ways, depending on the requirements of your program. Let us proceed further and understand the approaches:

Passing Array and Size:

The most common way to pass an array to a function is to pass the array itself (which decays to a pointer to the first element of the array) along with a separate parameter indicating the size of the array.

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int myArray[] = {1, 2, 3, 4, 5};
    int size = sizeof(myArray) / sizeof(myArray[0]);
    printArray(myArray, size);
    return 0;
}
Passing as a Pointer

You can also pass the array as a pointer. This method is essentially the same as the first since array arguments to functions are treated as pointers. We have already discussed this approach in detail.

void printArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", *(arr + i));
    }
    printf("\n");
}

int main() {
    int myArray[] = {1, 2, 3, 4, 5};
    int size = sizeof(myArray) / sizeof(myArray[0]);
    printArray(myArray, size);
    return 0;
}
Passing a Fixed-Size Array

If you know the size of the array in advance, you can specify the size in the function parameters. However, this method is less flexible as it only works with arrays of the specified size.

void printArray(int arr[5]) {
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int myArray[] = {1, 2, 3, 4, 5};
    printArray(myArray);
    return 0;
}
Passing a Multidimensional Array

For multidimensional arrays, you need to specify the size of the later dimensions.

void print2DArray(int arr[][3], int rows) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int myArray[2][3] = {{1, 2, 3}, {4, 5, 6}};
    print2DArray(myArray, 2);
    return 0;
}

When arrays are passed to a function, what is actually passed is the address of the first element (base address). The entire array is not copied.
It’s important to pass the size of the array as well, unless it’s a fixed-size array, as the function receiving the array won’t know the size otherwise.
Remember that changes made to the array elements in the function will affect the original array since the array is not passed by value, but rather, a pointer to its first element is passed.

When to Pass Array as a Parameter to a Function in C?

Passing an array as a parameter to a function in C is common and useful in various scenarios. Here are some situations when you might choose to do this:

SPONSOR AD
  • Processing Elements in Bulk: When you need to perform operations or calculations on multiple elements of an array, passing it to a function is efficient. This is common in tasks like sorting, searching, or aggregating data.
  • Modifying Array Contents: If you want to modify the contents of an array within a function and have these changes reflected in the original array, passing the array is the way to go. Remember, arrays in C are passed by reference (via their address), so any modifications in the function affect the original array.
  • Efficiency in Memory Usage: Passing the array as a pointer is memory-efficient, especially for large arrays. Since only the address is passed, it avoids the overhead of copying the entire array (which would happen if arrays were passed by value).
  • Implementing Algorithms: Many algorithms, such as sorting or searching algorithms, are naturally designed to work on data collection. Implementing these algorithms as functions that accept arrays as parameters makes your code more organized and reusable.
  • I/O Operations: For operations like reading from or writing to files, command line arguments, or interacting with hardware where data is naturally in arrays (like buffers), passing arrays to functions can simplify the code.
  • Using Arrays in Data Structures: When implementing data structures like heaps, graphs (adjacency matrices), or matrices for mathematical computations, you often use arrays. Functions operating on these structures will typically accept arrays as parameters.
  • Splitting Complex Tasks: If you have a complex task that can be divided into subtasks, each working on a part of an array, passing subarrays (or pointers to specific array positions) to functions can make your code more modular and testable.

In the next article, I will discuss How to Pass Structure as a Parameter to a Function in C Language with Examples. In this article, I explain How to pass an Array as a Parameter to a function in C Language. I hope you enjoy How to Pass an Array as a Parameter to a Function in the C Language article.