c
  1. c-return-an-array

C Return an Array

Syntax

data_type* function_name() {
  // Function body
}

Example

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

int* getNumbers() {
    static int numbers[5];
    printf("Enter 5 numbers:\n");
    for (int i = 0; i < 5; i++) {
        scanf("%d", &numbers[i]);
    }
    return numbers;
}

int main() {
    int* ptr;
    ptr = getNumbers();
    printf("You entered: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", *ptr);
        ptr++;
    }
    return 0;
}

Output

Enter 5 numbers:
2
4
6
8
10
You entered: 2 4 6 8 10

Explanation

In C programming language, it is possible to return an array from a function. The returned array can be assigned to a pointer, which can then be used to access the elements of the array.

The syntax of returning an array from a function involves declaring the data type of the array pointer in the function signature, followed by the function body and the return statement with the array name.

Use

Returning an array from a function can be useful in scenarios where a function needs to operate on an array, and the modified array needs to be accessed outside the function. It is also useful when the array size is not known at the time of declaration. In such cases, the array can be dynamically allocated inside the function and then returned to the calling function.

Important Points

  • When an array is returned from a function, it decays to a pointer to its first element.
  • The memory allocated for the array inside a function is deallocated automatically when the calling function completes.
  • To return an array from a function, you should declare the data type of the array pointer in the function signature, followed by the function body and the return statement with the array name.

Summary

The ability to return an array from a function allows C programmers to write more modular code and reuse functions that operate on arrays in different parts of their programs. By declaring the data type of the array pointer in the function signature, and returning the array name in the return statement, C programmers can return an array from a function and assign it to a pointer for further use.

Published on: