How Function Returning Pointer Variables In C?

In this tutorial discuss about function returning the pointer variable to the calling function.

So you must be careful, because local variables of function we can’t declare outside the function. Because they have scope only inside the function.

When a function return a pointer means here address will be returning and assign to the pointer variable inside main() function.

We understand it through the example:

#include <stdio.h>

int* larger(int*, int*);

int main()
{
    int a = 115;
    int b = 520;
    int *p;
    p = larger(&a, &b);
    printf("%d is larger",*p);
    return 0;
}

int* larger(int *x, int *y)
{
    if(*x > *y)
        return x;
    else
        return y;
}

The output of the above program is-

Output:
520 is larger

Explanation:

  • Inside main() function we declare two variables like, “a” and “b”.
  • Then one pointer variable *p is declared for return the pointer value from the called function i.e.
p = larger(&a, &b);

int* larger(int* x,int* y){
    .........
}
  • Inside the larger function, we compare two-pointer variables and return the address to the calling function.
int* larger(int* x,int* y)
{
       if(*x>*y)
            return x;
       else
            return y;
}
  • int* larger(int* ,int*) means the function returning the pointer in the form of address.

Safe Ways To Return Valid Pointer

  • When you are using arguments in function means passing arguments from calling function to called function, arguments are still live outside the function as well.
  • Also, use static local variables inside the function. Because static variables always exist till the end of the main() function, so they will be available throughout the program.

If you find any issue and interested to rewrite it then contact us.

Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 45

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply