How to Return a Pointer from a Function in C++?

In C++, we can return a pointer from a function which is useful when we want to return large data structures that cannot be returned by value. However, it must be done carefully to avoid memory leaks, dangling pointers, and other issues related to dynamic memory management. In this article, we will learn how to return a pointer from a function in C++.

Returning a Pointer from a Function in C++

To return a pointer from a function in C++, we need to declare a function with a pointer type, perform the necessary operations inside the function, and then return the pointer.

We also need to be careful that the data the pointer is pointing to is not a local to the function, otherwise it will be removed after the function return the value and the pointer returned will be pointing to the deallocated memory. To avoid this, use dynamic memory or use static qualifier.

Function Declaration While Returning Pointer

dataType* functionName() {
         // function body
         return ptr;
}

Here,

  • dataType is the type of data that the pointer points to.
  • functionName is the name of the function.
  • ptr is the pointer that the function returns.

C++ Program to Return a Pointer from a Function

The below example demonstrates how we can return a pointer to an array from a function in C++.

C++
// C++ program to return a pointer from a function

#include <iostream>
using namespace std;

// declaring the function with dynamic memory
int* createArray(int size)
{
    int* arr = new int[size];
    for (int i = 0; i < size; i++) {
        arr[i] = i;
    }

    // Return the pointer to the array
    return arr;
}

int main()
{
    // Function call
    int* myArray = createArray(5);

    // Use the array
    cout << "Array elements: ";
    for (int i = 0; i < 5; i++) {
        cout << myArray[i] << " ";
    }
    cout << endl;

    // Properly deallocate memory
    delete[] myArray;

    return 0;
}

Output
Array elements: 0 1 2 3 4 

Time Complexity: O(n), where n is the size of the array.
Auxiliary Space: O(n)

Note: When returning a pointer to a dynamically allocated memory, always remember to deallocate the memory when it is no longer needed. Failing to do so will result in a memory leak.


Contact Us