How to pass and return array from function in C?

Functions makes our program modular and maintainable. Big applications can have hundreds of functions.

Array is a data structure to store homogeneous collection of data. Arrays are equally important as functions. In programming we often use arrays and functions together.

Here in this post I will explain how to pass and return array from function in C programming.

How to pass single dimensional array to function?

In C you can pass single dimensional arrays in two ways. You can either pass it directly to a function. Or you can also pass it as a pointer to array.

Let us see both ways to pass single dimensional array to function one after one.

1. Passing array directly to function

You can pass single dimensional array directly to functions as you pass other variables.

void printArray(int arr[], int size)
{
    int i;

    printf("Array elements are: ");
    for(i = 0; i < size; i++)
    {
        printf("%d, ", arr[i]);
    }
}

int main()
{
    int arr[5];

    printArray(arr, 5);    // Pass array directly to function printArray

    return 0;
}

2. Passing array using pointer

Since array and pointers are closely related to each other. Hence you can also pass an array to function as pointer.

void printArray(int * arr, int size)
{
    int i;

    printf("Array elements are: ");
    for(i = 0; i < size; i++)
    {
        printf("%d, ", arr[i]);
    }
}

int main()
{
    int arr[5];

    printArray(arr, 5);    // Pass array directly to function printArray

    return 0;
}

Important Note: Arrays in C are passed as reference not by value. Which means any changes to array within the function will also persist outside the function.

How to return single dimensional array from function?

In C you cannot return an array directly from a function. But that does not impose a restriction on C language. There are two ways to return an array indirectly from a function.

1. Return pointer pointing at array from function

C does not allow you to return array directly from function. However, you can return a pointer to array from function.
Let us write a program to initialize and return an array from function using pointer.

#include <stdio.h>

/**
 * Function to return an array using pointers.
 * @return 	Pointer to array 
 */ 
int * getArray()
{
    int num[] = {1, 2, 3, 4, 5};
    int i;

    printf("Array inside function: ");
    // Print value of each array element
    for (i = 0; i < 5; ++i)
    {
        printf("%d\n", num[i]);
    }

    return num;
}

int main()
{
    int i;

    // Pointer to store array
    int * num;

    // Call getArray function to get pointer to array
    num = getArray();

    printf("Array outside function: \n");
    // Print value of each array element
    for (i = 0; i < 5; ++i)
    {
        printf("%d\n", num[i]);
    }

    return 0;
}

C compiler reports a warning message on compilation of above program.

a.c: In function 'getArray':
a.c:12:5: warning: function returns address of local variable [-Wreturn-local-addr]
     return num;
     ^

It complains about returning address of a local variable. We can return value of a local variable but it is illegal to return memory location that is allocated within function on stack. Since, after program control is returned from the function all variables allocated on stack within function are freed. Hence, returning a memory location which is already released will point at no man’s land.

But overlooking the compilers warning message let us run the program. On execution it produces following output which is somewhat weird.

Array inside function: 1
2
3
4
5
Array outside function: 3043328
8
6356668
4
6356940 

It is clear that inside function our array successfully got initialized, but something awful happened after returning it from function.

To overcome this you can either allocate array dynamically using malloc() function. Or declare array within function as static variable. Or you can pass the array to be returned as a parameter to the function.

However the best practice is to either pass array to return as parameter or allocate array dynamically using malloc() function.

2. Pass the returned array as parameter

Arrays in C are passed by reference, hence any changes made to array passed as argument persists after the function. So you can accept the output array you need to return, as a parameter to the function.

#include <stdio.h>

#define MAX_SIZE 10

/* Function delcaration to initialize array and return */
void getArray(int arr[], int size);

int main()
{
    int arr[MAX_SIZE];
    int i;

    // Call function to initialize array.
    getArray(arr, MAX_SIZE);

    printf("\n\nArray outside function: \n");
    for (i = 0; i < MAX_SIZE; i++)
    {
        printf("%d ", arr[i]);
    }

    return 0;
}

/** 
 * Function to initialize array.
 *
 * @arr     Integer array to initialize and return.
 * @size    Size of the array.
 */
void getArray(int arr[], int size)
{
    int i;

    printf("Enter elements in array: ");
    for (i = 0; i < size; i++)
    {
        scanf("%d", &arr[i]);
    }

    printf("\n\nArray inside function: \n");
    for (i = 0; i < size; i++)
    {
        printf("%d ", arr[i]);
    }
}

The above program on execution prints.

Enter elements in array: 1 2 3 4 5 6 7 8 9 10
Array inside function:
1 2 3 4 5 6 7 8 9 10

Array outside function:
1 2 3 4 5 6 7 8 9 10

How to pass multi-dimensional array to function?

Multi-dimensional arrays are passed in the same fashion as single dimensional. Which means you can pass multi-dimensional array to a function in two ways.

1. Passing multi-dimensional array directly to function

This is the simplest way to pass a multi-dimensional array to functions. Pass the array as other variables.

#include <stdio.h>

#define ROWS 3
#define COLS 3

/* Function declaration to print two dimensional array */
void printMatrix(int mat[][COLS]);

int main()
{
    int mat[ROWS][COLS] = {
                            {1, 2, 3}, 
                            {4, 5, 6},
                            {7, 8, 9}
                          };

    // Print elements of matrix using function
    printMatrix(mat);    

    return 0;
}

/** 
 * Function to accept two dimensional array and print
 * its elements.
 * 
 * @mat     Two dimensional integer array to print.
 */
void printMatrix(int mat[][COLS])
{
    int i, j;

    // Print elements of two dimensional array.
    printf("Elements in matrix: \n");
    for (i = 0; i < ROWS; i++)
    {
        for (j = 0; j < COLS; j++)
        {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

2. Passing multi-dimensional array to function using pointer

#include <stdio.h>

#define ROWS 3
#define COLS 3

/* Function declaration */
void inputMatrix(int (*mat)[COLS]);
void printMatrix(int mat[][COLS]);

int main()
{
    int mat[ROWS][COLS];

    // Input elements in matrix using function
    inputMatrix(mat);

    // Print elements of matrix using function
    printMatrix(mat);    

    return 0;
}

/**
 * Function to accept a two dimensional array and input
 * elements in matrix from user.
 * 
 * @mat     Two dimensional integer array to store user input.
 */
void inputMatrix(int (*mat)[COLS])
{
    int i, j;

    // Input elements in 2D matrix
    printf("Enter elements in 2D matrix: \n");
    for (i = 0; i < ROWS; i++)
    {
        for (j = 0; j < COLS; j++)
        {
            scanf("%d", (*(mat + i) + j));
        }
    }
}

/** 
 * Function to accept a two dimensional array and print
 * its elements.
 * 
 * @mat     Two dimensional integer array to print.
 */
void printMatrix(int (*mat)[COLS])
{
    int i, j;

    // Print elements of two dimensional array.
    printf("Elements in matrix: \n");
    for (i = 0; i < ROWS; i++)
    {
        for (j = 0; j < COLS; j++)
        {
            printf("%d ", *(*(mat + i) + j));
        }
        printf("\n");
    }
}

Important Note: int (*mat)[COLS] and int * mat[COLS] both are different. First is a pointer to array whereas second is array of pointers.

How to return multi-dimensional array from function?

Returning multi-dimensional array from function is similar as of returning single dimensional array. Which means you can either return a pointer to array or pass the array to return as a function parameter.

#include <stdio.h>

#define ROWS 3
#define COLS 3

/* Function declaration */
void matrixAddition(int mat1[][COLS], int mat2[][COLS], int res[][COLS]);
void printMatrix(int mat[][COLS]);

int main()
{
    int mat1[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int mat2[ROWS][COLS] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};    

    // Resultant matrix which is passed to function. 
    // Function performs calculation and fills the array
    int res[ROWS][COLS];

    // Input elements in matrix using function
    matrixAddition(mat1, mat2, res);

    // Print resultant array
    printMatrix(res);    

    return 0;
}

/**
 * Function to add two matrices and return the resultant matrix.
 * 
 * @mat1    First matrix to add.
 * @mat2    Second matrix to add.
 * @res     The resultant matrix that will be filled with addition 
 *          result.
 */
void matrixAddition(int mat1[][COLS], int mat2[][COLS], int res[][COLS])
{
    int i, j;
    for(i = 0; i < ROWS; i++)
    {
        for(j = 0; j < COLS; j++)
        {
            res[i][j] = mat1[i][j] + mat2[i][j];
        }
    }
}

/** 
 * Function to accept a two dimensional array and print
 * its elements.
 * 
 * @mat     Two dimensional integer array to print.
 */
void printMatrix(int mat[][COLS])
{
    int i, j;

    // Print elements of two dimensional array.
    printf("Elements in matrix: \n");
    for (i = 0; i < ROWS; i++)
    {
        for (j = 0; j < COLS; j++)
        {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

Conclusion

We learned to pass array and return array from a function. Passing an array to function is not big deal and is passed as other variables. However always mind that arrays are passed by reference. Returning an array from function is not as straight as passing array to function. There are two ways to return an array from function. But I personally prefer to pass array to return as argument and fill the resultant array inside function with processed result.