Back to C++
2026-04-135 min read

C++ Return Array from Functions

Learn C++ Return Array from Functions step by step with clear examples and exercises.

Title: Returning Arrays from Functions in C++

Why This Matters

In C++, functions can return various data types such as int, float, and bool. However, it's also possible to design a function that returns an array. Understanding how to do this is essential for creating efficient and reusable code. This knowledge can be crucial in real-world programming scenarios, interviews, or debugging complex projects.

Importance of Returning Arrays from Functions:

  • Allows for efficient data manipulation and reuse
  • Simplifies complex calculations by encapsulating them within functions
  • Enables the creation of customizable and flexible code

Prerequisites

To understand returning arrays from functions in C++, you should have a solid grasp of the following concepts:

  • Basic C++ syntax (variables, operators, and control structures)
  • Arrays and pointers
  • Function definitions and calling functions
  • Memory management using new, delete, and delete[]

Core Concept

A function can return an array by creating a dynamic array on the heap using new and then returning a pointer to that memory. However, it's important to remember that the caller is responsible for deleting the allocated memory when it's no longer needed, using the delete[] operator.

Advantages of Dynamic Memory Allocation:

  • Allows for variable-sized arrays
  • Eliminates the need for preallocating large amounts of memory
  • Enables efficient memory management by only allocating what is necessary

Dynamic Array Creation

int* createArray(int size) {
int* arr = new int[size];

// Initialize the array here if needed

return arr;
}

In this example, we define a function createArray() that takes an integer argument representing the array size and returns a pointer to an array of integers. The caller is responsible for freeing the memory using delete[].

Dynamic Array Initialization

Initializing a dynamic array can be done during creation or afterward, depending on your needs.

int* createArray(int size) {
int* arr = new int[size];

for (int i = 0; i < size; ++i) {
arr[i] = i * 2; // Initialize the array with even numbers
}

return arr;
}

Memory Deallocation

When you're done using a dynamically allocated array, it's important to deallocate the memory to avoid memory leaks.

int* createArray(int size) {
int* arr = new int[size];

// ...

delete[] arr; // Don't forget to free the memory!

return arr;
}

Worked Example

Let's create a function that returns an array containing Fibonacci numbers up to a given index.

#include <iostream>
using namespace std;

int* fibonacci(int n) {
int* fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;

for (int i = 2; i <= n; ++i) {
fib[i] = fib[i - 1] + fib[i - 2];
}

return fib;
}

void printFibonacci(int* fib, int n) {
for (int i = 0; i < n; ++i) {
cout << fib[i] << " ";
}
cout << endl;
}

int main() {
const int FIB_SIZE = 10;
int* fibArray = fibonacci(FIB_SIZE);

printFibonacci(fibArray, FIB_SIZE);

delete[] fibArray; // Don't forget to free the memory!

return 0;
}

In this example, we define a fibonacci() function that returns an array containing Fibonacci numbers up to a given index. The printFibonacci() function prints the contents of a Fibonacci array. In the main() function, we call these functions to create and print a Fibonacci array of 10 numbers.

Common Mistakes

Forgetting to free memory

When you allocate memory using new, it's important to remember to deallocate it using delete[]. If you forget to do this, your program will have a memory leak, which can lead to unpredictable behavior and crashes.

int* createArray(int size) {
int* arr = new int[size];

// ...

// Forgetting to free the memory!
}

Returning a local array

If you return a local array from a function, the array will be destroyed when the function returns. This can lead to undefined behavior and crashes. To avoid this, use dynamic memory allocation with new.

int createArray(int size) {
int arr[size]; // Local array

// ...

return arr; // Don't do this!
}

Not checking the return value of new

When you use new, it's important to check whether the allocation was successful. If new fails, it returns a null pointer. Using a null pointer can lead to crashes or unpredictable behavior.

int* createArray(int size) {
int* arr = new int[size]; // What if new fails?

// ...

return arr;
}

To fix this, check the return value of new and handle the case where it returns a null pointer.

Practice Questions

  1. Write a function that returns an array containing the first n prime numbers.
  2. Write a function that takes two arrays as arguments and returns their sum element-wise.
  3. Write a function that finds the maximum element in an array.
  4. Write a function that sorts an array using bubble sort.

Subheadings:

  • Common Mistakes

+ Forgetting to free memory

+ Returning a local array

+ Not checking the return value of new

  • Practice Questions
  1. Prime numbers array
  2. Element-wise sum
  3. Maximum element finder
  4. Bubble sort implementation
  • FAQ

+ Why can't I return a local array from a function?

+ What happens if I forget to free the memory allocated using new?

+ What should I do if new fails and returns a null pointer?

FAQ

Q: Why can't I return a local array from a function?

A: Local arrays have automatic storage class, which means they are created on the stack during function execution and destroyed when the function returns. If you return a local array, it will be an invalid pointer to memory that no longer exists. To avoid this, use dynamic memory allocation with new.

Q: What happens if I forget to free the memory allocated using new?

A: When you allocate memory using new, it's important to deallocate it using delete[] when you no longer need it. If you don't do this, your program will have a memory leak. This can lead to unpredictable behavior and crashes.

Q: What should I do if new fails and returns a null pointer?

A: When you use new, it's important to check whether the allocation was successful by checking the return value against a null pointer. If new fails, it returns a null pointer. You can handle this case by either throwing an exception or returning an error code. It's also good practice to check the size of the array you want to allocate before calling new.

Note: This FAQ section can be expanded with more questions and answers as needed.

C++ Return Array from Functions | C++ | XQA Learn