×

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

Different ways to Declare the Variable as Constant in C

There are a wide range of ways of making the variable as steady Using const keyword: The const catchphrase permits a software engineer to inform the compiler that a specific variable should...

5 minutes read.

Find the Largest Three Distinct Elements in an Array using C/C++

In this tutorial, we will demonstrate how to use a C/C++ programme to locate the highest three different elements in an array. C/C++ Program to Find the Largest Three Different Elements...

3 minutes read.

Merge Sort in C

The merge sort follows the principle of the divide and conquers algorithm. Firstly it divides the input of an array into two halves and then calls itself for the two...

4 minutes read.

How to measure time taken by a function in C?

Measuring the time taken by a function is quite a complex task, because numerous methods are frequently not transferable to other platforms, measuring the execution time of a C programs...

5 minutes read.

C program to Store Information of Students Using Structure

What is the Structure in C? User-defined data types include structures. Structures aid your ability to combine things of various categories into a single group. Like arrays, it operates similarly. A...

3 minutes read.

Actual and Formal Parameters

Any variable declared within the parenthesis is referred to as the parameters during the function declaration. Parameters tell the function about the argument datatype, their order, and the number of...

5 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

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.

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.

Advantages of Dynamic Memory Allocation in C

Dynamic Memory Allocation Dynamic memory allocation is a process of assigning or allocating memory to a variable during the execution of a program. Dynamic memory allocation provides storage according to the...

3 minutes read.

Bar3d() function in C Graphics

The bar3d function is used to create a 2-dimensional filled-in rectangular bar. We can also create three-dimensional shapes in C using helpful function. The first step in creating this 3D...

3 minutes read.

Return array from function in C

Return array from function in C C programming does not require the return to a function of a whole array as an argument. However, you can return a pointer to an array without...

2 minutes read.

Dynamic memory allocation

Dynamic memory allocation is used to allocate the memory at runtime. It has following function within <stdlib.h> header file. Function Syntax malloc() malloc (number *sizeof(int)); calloc() calloc (number, sizeof(int)); realloc() realloc (pointer_name, number * sizeof(int)); free() free (pointer_name); malloc() function The process...

2 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.

Types of Pointers in C

Pointers in C A pointer is a variable and this variable contains the address of another variable, i.e it’s a variable which has the address of another variable as its value....

4 minutes read.

Library Functions in C

What are library functions? Library functions are the built-in functions (functions provided by the system) which are stored in the library. The library is the common location where these functions are...

3 minutes read.

Difference between Pre-increment and Post-increment in C

Increment operators are the kind of operators that are used to increment the cost of the operand by way of 1. In different words, the increment operator is an operator...

4 minutes read.

Error handling in C

Error handling in C: The C programming standard does not provide direct convenience for handling the errors. However, being a system programming language, it definitely will give access to handling...

4 minutes read.

Palindrome Number in C

What is a Palindrome? A number that doesn't change when reversed is known as a palindrome. We reverse a number and compare it to the original number to determine whether it is...

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.