0
0
CHow-ToBeginner · 3 min read

How to Return Array from Function in C: Simple Guide

In C, you cannot return an array directly from a function, but you can return a pointer to an array or use a static array inside the function. Use int* to return a pointer to the first element of the array or declare the array as static inside the function to keep it valid after the function ends.
📐

Syntax

To return an array from a function in C, you typically return a pointer to the array's first element. The function signature uses a pointer type like int*. Alternatively, you can return a pointer to a static array declared inside the function.

  • Pointer return type: The function returns int* pointing to the array.
  • Static array: Declared with static to keep it alive after function returns.
c
int* functionName() {
    static int arr[5];
    // fill arr
    return arr;
}
💻

Example

This example shows a function returning a pointer to a static array. The main function prints the returned array elements.

c
#include <stdio.h>

int* getArray() {
    static int arr[5] = {10, 20, 30, 40, 50};
    return arr; // return pointer to static array
}

int main() {
    int* ptr = getArray();
    for (int i = 0; i < 5; i++) {
        printf("%d ", ptr[i]);
    }
    return 0;
}
Output
10 20 30 40 50
⚠️

Common Pitfalls

Common mistakes include returning a pointer to a local (non-static) array, which becomes invalid after the function ends, causing undefined behavior. Another mistake is trying to return an array directly, which C does not allow.

Correct approach is to use static arrays or dynamically allocate memory (with malloc) and return the pointer.

c
/* Wrong: returning pointer to local array (invalid after return) */
int* wrongFunction() {
    int arr[3] = {1, 2, 3};
    return arr; // arr is local and destroyed after function ends
}

/* Right: using static array */
int* rightFunction() {
    static int arr[3] = {1, 2, 3};
    return arr; // valid after function returns
}
📊

Quick Reference

  • Use static keyword for arrays inside functions to keep them valid after return.
  • Return a pointer (int*) to the first element of the array.
  • Do not return pointers to local non-static arrays.
  • Alternatively, use dynamic memory allocation with malloc and remember to free it later.

Key Takeaways

You cannot return arrays directly in C; return a pointer to the array instead.
Use static arrays inside functions to keep the array valid after return.
Never return pointers to local non-static arrays as they become invalid.
Dynamic memory allocation is another way to return arrays safely.
Always manage memory properly when using dynamic allocation.