Pointers and Functions in C

In this lesson, you will learn about function pointer in C, its usage, and how to pass a pointer to a function as a parameter.

Function Pointer in C

As we learned from the lesson User Defined Functions in C, a function can return a Data Type, such as float, integer, etc. In programming, a function can also return a pointer Data Type. To do so, you will need to create a function that returns a pointer type:

int* PointerFunction()
{
static int a = 30;
return (&a);
}

Now, call the function above from the main() function:

int main() 
{ 
     
    int* intPointer; 
   
    intPointer= PointerFunction(); 
  
    printf("%p\n", intPointer); 
    printf("%d\n", *intPointer); 
    return 0; 
}

Output

0x601040
30

Now you are probably wondering why the variable a is declared static. A static variable preserves its value even if it is out of the program scope. In C, a compiler makes a stack for the function call:

intPointer= PointerFunction();

As soon as the function exits, the function stack is destroyed, causing all variables to lose their values if declared as non-static.

Pass a pointer to a function in C as a parameter

A function in C can take a pointer as an argument, just like other Data Types.

#include <stdio.h>

int* Greater(int*, int*);

void main()
{
    int x = 12;
    int y = 14;
    int *intPointer;
    intPointer = Greater(&x, &y);
    printf("%d is Greater",*intPointer);
}
// Pass pointers arguments
int* Greater(int *a, int *b)
{
    if(*a > *b)
        return a;
    else
        return b;
}

Output

14 is Greater

Summary

  • Functions in C can return a pointer Data Type.
  • A pointer can be passed to a function as a parameter.
Back to: Learn C Programming > Pointers in C

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.