Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Returning pointer from function

Previously we have seen that a function can return any variable to the caller function.
Similarly, functions in C can return pointer variable to the caller function.

Syntax

return_type  *function_name(parameter_list)
{
    // function body
}

Example

#include <stdio.h>
int *returnPointer(int *p);
int main()
{
    int i=10;
    int *ptr1, *ptr2;
    ptr1=&i;
    ptr2=returnPointer(&i);
    printf("\n *ptr1 = %d",*ptr1);
    printf("\n *ptr2 = %d",*ptr2);
    return 0;
}

int *returnPointer(int *pt)
{
    return pt;
}

Output

*ptr1 = 10
*ptr2 = 10

For the better understanding of the above program look at the diagram shown below:

C Programming Language Returning Pointer from Function

Returning an address of the local variable

It is a bad idea to return the address of local variable from the caller function to called function.

Example

#include <stdio.h>
int *returnFunc();
int main()
{
    int *ptr=returnFunc();
    printf("\n *ptr = %d",*ptr);
    printf("\n *ptr = %d",*ptr);
    printf("\n *ptr = %d",*ptr);
    return 0;
}

int *returnFunc()
{
    int i=10;
    return &i;
}

Output

*ptr = 10
*ptr = 0
*ptr = 0

Above program will not give the result as expected because we have returned an address of the local integer variable i.
When we call the function returnFunc(), a memory with certain address will be occupied in the stack for local variable i having value 10.

C Programming Language Returning an Address of Local Variable Stack Representation 1

But when we try to return the address of i to the caller function, function returnFunc()  gets terminate and thus local variable i get destroyed from stack memory.

C Programming Language Returning an Address of Local Variable Stack Representation 2

Now the address returned to the caller function is 2000.
This address is assigned to the integer pointer ptr. Now ptr points to the address 2000.

C Programming Language Returning an Address of Local Variable Stack Representation 3

But local variable present at address 2000 is already destroyed. And ptr is pointing to the variable that does not exist.
If we try to dereference pointer ptr, we will get unexpected result getting a warning from compiler as, [Warning] function returns address of local variable.
Therefore it is a very bad idea to return the address of a local variable to the caller function.

Note

If we want to return the address of a local variable to the caller function, then it should be declared as static.
The static variable is not destroyed till the end of a program.

Example

#include <stdio.h>
int *returnFunc();
int main()
{
    int *ptr=returnFunc();
    printf("\n *ptr = %d",*ptr);
    printf("\n *ptr = %d",*ptr);
    printf("\n *ptr = %d",*ptr);
    return 0;
}

int *returnFunc()
{
    static int i=10;
    return &i;
}

Output

*ptr = 10
*ptr = 10
*ptr = 10

 

Leave a reply