Function Returning Pointer
Introduction
A function can return a pointer
— i.e., the address of a variable instead of its actual value.
Returning a pointer is useful when:
- Return
large data efficiently (without copying)
- Modify
variables
outside the function
- Return
arrays or dynamically allocated memory
Syntax
datatype*
function_name(parameters);
Example:
int* getNumber();
Function getNumber() will return
a pointer to int (i.e., an int address).
Example 1 –
Returning Address of a Variable
#include <iostream>
using namespace std;
int* findMax(int* a, int* b) {
if (*a > *b)
return a; // return address of a
else
return b; // return address of b
}
int main() {
int x = 10, y = 20;
int* result = findMax(&x, &y);
cout << "Maximum = " << *result;
return 0;
}
Output:
Maximum = 20
Example 2 –
Returning Pointer from Function (with Local Variable )
Note:- Never
return a pointer to a local variable — it becomes invalid when the
function ends.
Wrong Example:
int* demo() {
int x = 10;
return &x; // x is
local variable → memory destroyed after function ends
}
This leads to undefined behavior.
Correct Way: Use
static or new
(a) Using a static variable:
int* demo() {
static int x = 10;
return &x; // valid, x
persists even after function ends
}
(b) Using new (Dynamic Memory):
int* demo() {
int* p = new int;
*p = 10;
return p; // valid, memory
remains until deleted manually
}
Example 3 –
Returning Pointer Using Dynamic Memory
#include <iostream>
using namespace std;
int* createArray(int n) {
int* arr = new int[n]; //
dynamically allocate memory
for (int i = 0; i < n; i++)
arr[i] = i + 1;
return arr; // return base
address
}
int main() {
int n = 5;
int* p = createArray(n);
cout << "Array elements: ";
for (int i = 0; i < n; i++)
cout << p[i] << "
";
delete[] p; // free memory
return 0;
}
Output:
Array elements: 1 2 3 4 5
Real-Life Uses
- Returning the array base address
- Returning a structure or object pointer
- Allocating
memory using new
- Pointer-based
linked list, tree, stack, etc.
0 Comments