C Program to Return Pointer from Function
Write a C program return pointer from function.
- Two integers num1 and num2 are declared and initialized with values.
- The function getMax is called with the addresses of num1 and num2.
- getMax returns a pointer to the larger value by dereferencing and comparing the values.
- The returned pointer is used to print the larger number using *maxPtr.
Example : pgm.c
#include <stdio.h> // Function that returns a pointer to the larger of two numbers int* getMax(int *a, int *b) { if (*a > *b) return a; else return b; } int main() { int num1 = 25, num2 = 40; int *maxPtr; maxPtr = getMax(&num1, &num2); printf("The larger number is: %d\n", *maxPtr); return 0; }
Output :
The larger number is: 40