Returning a Pointer from a Function in C
Last updated on July 27, 2020
We have already seen a function can return data of types int , float, char etc. Similarly, a function can return a pointer to data. The syntax of a function returning a pointer is as follows.
Syntax: type *function_name(type1, type2, ...);
Some examples:
1 2 3 | int *func(int, int); // this function returns a pointer to int
double *func(int, int); // this function returns a pointer to double
|
The following program demonstrates how to return a pointer from a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include<stdio.h>
int *return_pointer(int *, int); // this function returns a pointer of type int
int main()
{
int i, *ptr;
int arr[] = {11, 22, 33, 44, 55};
i = 4;
printf("Address of arr = %u\n", arr);
ptr = return_pointer(arr, i);
printf("\nAfter incrementing arr by 4 \n\n");
printf("Address of ptr = %u\n\n" , ptr);
printf("Value at %u is %d\n", ptr, *ptr);
// signal to operating system program ran fine
return 0;
}
int *return_pointer(int *p, int n)
{
p = p + n;
return p;
}
|
Expected Output:
1 2 3 4 5 6 7 | Address of arr = 2686736
After incrementing arr by 4
Address of ptr = 2686752
Value at 2686752 is 55
|
How it works:
Since the name of an array is a pointer to the 0th element of the array. Here we are passing two arguments to the function return_pointer()
. The arr
is passed using call by reference (notice that name of the array is not preceded by &
operator because the name of the array is a constant pointer to the 0th element of the 1-D array) and i
is passed using call by value. Inside the function pointer p
is incremented by n
and reassigned to p
. Finally, the pointer p
is returned to the main()
function and reassigned to ptr
.
Never return a pointer to local variable from a function.
Consider the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<stdio.h>
int *abc(); // this function returns a pointer of type int
int main()
{
int *ptr;
ptr = abc();
return 0;
}
int *abc()
{
int x = 100, *p;
p = &x;
return p;
}
|
Can you point out the problem with above code?
In the function abc()
we are returning a pointer to the local variable. Recall that a local variable exists only inside the function and as soon as function ends the variable x
cease to exists, so the pointer to it is only valid inside the function abc()
.
Even though the address returned by the abc()
is assigned to ptr
inside main()
, the variable to which ptr
points is no longer available. On dereference the ptr
you will get some garbage value.
Note: Sometimes you may even get the correct answer i.e 100
, but you must never rely on this behaviour.
Load Comments