Define pointer. Flow to you return pointers from functions? Explain with example.

Answers

This answer is not selected as best answer. This answer may not be sufficient for exam.

Your limit has been exceed. We have implemented this system because, We got difficulty on managing our servers. Please donate some amount to remove this limit.

Quota: 0 / 30

Donate

A pointer is a variable that contains a memory address of data or another variable. Normally, a pointer variable is declared to some type, like any other variables, so that it will work only with data of given type.

The syntax of pointer is

data_type *pointer;

C Program allows us to return a pointer from a function. To do this, we have to declare the function returning pointer

int *function(){
   
   // body of function
}

Example that return pointer from function

This is the example to check the greatest number among two number.

#include <stdio.h>

// function declaration
int *getMax(int *, int *);

int main(void){

    int x = 5;
    int y = 10;

    // pointer variable
    int *max = NULL;

    max = getMax(&x, &y);

    // print the greater value
    printf("Max value: %d\n", *max);

    return 0;
}

// function definition
int *getMax(int *m, int *n){

    if (*m > *n){
        return m;
    }else{
        return n;
    }

}

The output of above program is

Max value: 10

In the above example, First we have declared two integer variables x and y that has 5 and 10 value respectively. And also we have declared null pointer with name max.

Then we have called the function getMax that return pointer. On this function, we have passed address of the variables x and y. 

if the value pointed by pointer m is greater than n then, getMax function return the address stored in the pointer variable m otherwise it returns the address stored in the pointer variable n.

 

If you found any type of error on the answer then please mention on the comment or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .