Skip to main content

Can a function return an array

Short answer

A function cannot return a whole array, but can return a pointer to the first element. That pointer must address memory that outlives the function, such as a static array or dynamically allocated memory. Returning a local array’s address is invalid.

Can a function return an array to the calling function? Explain with example.

No. A C function cannot return a whole array by value, because an array name is not an assignable value and the return type cannot be an array type. However, it can return a pointer to the first element of an array, and the caller then uses that pointer like an array.

Important rule: the returned pointer must point to memory that still exists after the function ends. A normal local array is destroyed when the function returns, so it must not be returned. Safe choices:

  1. A static array inside the function.
  2. An array allocated with malloc().
  3. An array passed in by the caller (the function fills it).
  4. An array inside a structure, since a structure can be returned by value.

Example (static array)

#include <stdio.h>

int *makeSquares(void)
{
    static int sq[5];                 /* static: lives after the function ends */
    for (int i = 0; i < 5; i++)
        sq[i] = (i + 1) * (i + 1);
    return sq;                        /* returns address of first element */
}

int main(void)
{
    int *p = makeSquares();
    for (int i = 0; i < 5; i++)
        printf("%d ", p[i]);
    printf("\n");
    return 0;
}

Output:

1 4 9 16 25

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →