×

How to return a Pointer from a Function in C?

In the C programming language, pointers are variables that hold the address memory location of another variable. We could also input pointers to a function and return pointers from a function. However, returning the location of the local variable outside of the function is not recommended since it will be out of scope once the method returns.

Syntax for a function declaration that returns a pointer:

 returnType *func_name(parameter);

Where, “returnType” denotes the type of pointer returned by the function “func_name” and here "parameter" is a list of the function's optional arguments.

For example, We declare a function called "Max_numbers" that accepts two integer pointer variables as parameters and returns an integer pointer.

int *Max_numbers(int * , int *);

Example – 1:

For example, the Max numbers( ) function returns an integer pointer, which is the location of a variable with the bigger value.

#include <stdio.h>
/* Function Declaration */
int *Max_numbers(int *, int *);
int main(void){
	/* Define integer data-type variables */
	int a = 180;
	int b = 360;
	/* Define pointer variable*/
	int *maxi = NULL;
/* Get the variable address with the highest value by supplying the addresses of a and b to the function Max_functions( ) */
maxi = Max_numbers(&a, &b);
/* print the greater value using printf function */
printf(“Maximum Value:%d\n”,*maxi);
return 0;
} 
/* Define Function */
int *Max_numbers(int *x, int *y) {
	/* Return the address contained in the pointer variable ‘a’ if the value given by pointer ‘x’ is bigger than ‘y’ */
	if (*x > *y){
		return x;
	}
	/* else return the address stored in the pointer variable ‘y’ */
	else {
		return y;
	}
} 

Output:

How to return a Pointer from a Function in C

We can represent these two variables ‘a’ and  ‘b’ in the memory location as follows

int x = 180;

Assume the address location of the variable ‘a’ which has value 180 is 6550.

int y = 360;

Assume the address location of the variable ‘b’ which has value 360 is 7550.

Then we make an integer pointer variable “maxi” that has the address of the variable with the higher value. At this time, the pointer variable “maxi” is stored at address location 8550 with the value NULL.

Following that, we use the Max_numbers() method, supplying the addresses of variables ‘a’ and ‘b.’ In the Max_numbers() function, parameter ‘x’ receives the address of variable ‘a’ and parameter ‘y’ gets the address of variable ‘b.’

As a result, integer pointer variable x retains the address of variable a, i.e., 6550, and is assigned memory location 10850 (assume).

Similarly, the integer pointer variable y is assigned memory position 10852 and stores the address of variable b, which is 7550.

Now we're comparing to see whether *x > *y, which means that the value indicated by the pointer variable x is bigger than the value indicated by the pointer variable y.

The value shown by the pointer variable x is 180, while the value indicated by the pointer variable y is 360. As a result, the if block is disregarded, and the else block is run, returning the address held in the pointer variable y, 7550, which is the address of the variable b.

As a result, the address of variable b is returned by the Max_numbers( ) method and placed in the integer pointer variable maxi. So, the maxi variable now has the address 7550.

Finally, we display the value saved at position 7550 using the pointer variable maxi. This gives us the bigger value, i.e., 360.

Example -2:

#include <stdio.h>
 /* Function returning the pointer variable */
int *function( ) {
    int K = 100;
    return (&K);
}
 /* Main block code */
int main( ) {
    /* Pointer Declaration */
    int *q;
  /* Calling the function */
    q = function( );
     printf("%p\n", q);
     printf("%d\n", *q);
    return 0;
}

Output:

How to return a Pointer from a Function in C

Because "K" was local to the function, the above program code will generate a segmentation fault.

The fundamental cause of this situation is that the compiler always creates a "stack" when calling a function. When a function quits, the function stack is likewise erased, and the local variables of the function are no longer in scope.

Static Variables

Static variables have the property of holding their value even when they are removed from their scope. To implement the idea of returning a pointer from a function in the C language, the local variable must be declared as a static variable.


Related Topics

abs() function in C

abs() function is a built-in function present in the stdlib.h header file. It returns an integer value. abs() function converts a negative value into a positive value. For example, if...

4 minutes read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

#error #pragma in C

#error, #pragma in C #error, also known as the error directive in the C language. It will not allow you to make any compilation fail and immediately issues a statement which...

4 minutes read.

Volatile in C

Introduction A volatile keyword is a qualifier in C. Qualifiers are nothing but keywords which are used to modify the properties of a variable. Qualifiers are of two types: 1) Const The const type...

3 minutes read.

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

Snake Game in C

Snake game in C is basic desktop console program which was created in 1970’s. It is an old classic game which was played by every child across the world. This...

4 minutes read.

Binomial Coefficient Program in C

What is Binomial coefficient? In the given set of n possibilities, the binomial coefficient(n,k) indicates the order of choosing 'K' results from those possibilities. Binomial coeeficient of posistive n and k...

3 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Matrix Multiplication in C

Matrix Multiplication in C Matrix multiplication in C: Two matrices can be added, subtracted, multiplied, and divided. To do so, we take input from the consumer for row number, column number, first element matrix,...

3 minutes read.

Prime Number Program in C using for Loop

In this article, we will know about the procedure of checking whether a natural number inputted by the user is a prime number or non-prime number. Definition of the prime number A...

3 minutes read.

Associativity of Operators in C

What is an Associativity operator? Two operators with equal priority are connected by employing their association when they are present in an expression. There are two different types of associativity: left to rightright...

4 minutes read.

OpenGL in C

OpenGL stands for Open Graphics Library. It is a low-level, widely supported modeling and rendering software package that is widely available across all the platforms. It is an API used...

4 minutes read.

How to lock top row in Excel

How to lock top row in excel While working with an Excel spreadsheet, the user utilizes the rows and columns to enter the details under various headings. Sometimes while scrolling the...

4 minutes read.

What are linker and loader in C

Linker and loader are utility programs that have a significant role in executing a program. Linker: A linker is a program that joins the object files produced by the assembler/ compiler...

3 minutes read.

Random function in C

Random function in C In the C programming language, the rand() is a function used for Pseudo Random Number Generator (PRNG). The random number generated by the rand() function is not...

4 minutes read.

Conditional Operator in C

In C programming language, the conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. The syntax of conditional operator in C is...

3 minutes read.

Garbage in C

Garbage in C The C programming language is a perfect fit for embedded systems as it provides low level control, structured programming, and portability. On the contrary, it does not provide...

3 minutes read.

Fseek Function in C

The fseek function is a function in the C standard library that changes the position of the file pointer in a stream-oriented file. It is typically used to move the...

3 minutes read.

Execution flow of C program

There are various steps of the execution of the C program that is given below. The following step of the execution Write source codes Preprocess Compile Link edit Load Execute Editor or...

1 minute read.

Break, continue and goto statement in C

Break statement Break statement is used to break the process of a loop (while, do while and for) and switch case. Syntax: break; Example 1 while(test Expression) { // codes if(condition for break){ break; } // codes } Example 2 For(int it, condition,...

1 minute read.