How to return a Pointer from a Function in C

Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns.

Program 1:

The below program will give segmentation fault since ‘A’ was local to the function:

C

// C program to illustrate the concept of // returning pointer from a function // Function returning pointer // Driver Code // Declare a pointer // Function call printf ( "%p\n" , p); printf ( "%d\n" , *p);


Output:
Below is the output of the above program:

Explanation:

The main reason behind this scenario is that compiler always make a stack for a function call. As soon as the function exits the function stack also gets removed which causes the local variables of functions goes out of scope.

Static Variables have a property of preserving their value even after they are out of their scope. So to execute the concept of returning a pointer from function in C you must define the local variable as a static variable.

Program 2:

C

// C program to illustrate the concept of // returning pointer from a function // Function that returns pointer // Declare a static integer static int A = 10; // Driver Code // Declare a pointer // Function call // Print Address printf ( "%p\n" , p); // Print value at the above address printf ( "%d\n" , *p); Output:
0x601038 10
Like Article -->

Please Login to comment.

Similar Reads

C - Pointer to Pointer (Double Pointer)

Prerequisite: Pointers in C The pointer to a pointer in C is used when we want to store the address of another pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to cha

5 min read What is a Pointer to a Null pointer

NULL pointer in C At the very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL are To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet. C/C++ Code int* pInt = NULL; To check for a null pointer before accessing an

2 min read Pointer to an Array | Array Pointer

Prerequisite: Pointers Introduction Consider the following program: [GFGTABS] C #include<stdio.h> int main() < int arr[5] = < 1, 2, 3, 4, 5 >; int *ptr = arr; printf("%p\n", ptr); return 0; > [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer

9 min read C Function Arguments and Function Return Values

Prerequisite: Functions in C A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values. Hence the function prototype of a function

6 min read How to declare a pointer to a function?

While a pointer to a variable or an object is used to access them indirectly, a pointer to a function is used to invoke a function indirectly. Well, we assume that you know what it means by a pointer in C. So how do we create a pointer to an integer in C? Huh..it is pretty simple. int *ptrInteger; /*We have put a * operator between int and ptrInt

2 min read How to Create a Typedef for a Function Pointer in C?

In C, a function pointer is a variable that stores the address of a function that can later be called through that function pointer. The typedef is a keyword used to create an alias or alternative name for the existing data types. In this article, we will learn how to create a typedef for a function pointer in C. Typedef for a Function Pointer in C

2 min read Function Pointer in C

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer. [GFGTABS] C++ #include <stdio.h> // A normal function with an int parameter // and void return type void fun(int a) < printf("Value of a is %d\n", a);

6 min read How can I return multiple values from a function?

We all know that a function in C can return only one value. So how do we achieve the purpose of returning multiple values. Well, first take a look at the declaration of a function. int foo(int arg1, int arg2); So we can notice here that our interface to the function is through arguments and return value only. (Unless we talk about modifying the glo

2 min read Pointer vs Array in C

Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the & operator array is an alias for &array[0

1 min read NULL Pointer in C

The Null Pointer is the pointer that does not point to any location but NULL. According to C11 standard: “An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guarantee

4 min read C | Pointer Basics | Question 1

What is the output of following program? # include <stdio.h> void fun(int x) < x = 30; >int main() < int y = 20; fun(y); printf("%d", y); return 0; >(A) 30 (B) 20 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: Parameters are always passed by value in C. Therefore, in the above code, value of y is not modified using

1 min read C | Pointer Basics | Question 2

Output of following program? # include <stdio.h> void fun(int *ptr) < *ptr = 30; >int main() < int y = 20; fun(&y); printf("%d", y); return 0; >(A) 20 (B) 30 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value

1 min read C | Pointer Basics | Question 3

Output of following program? #include <stdio.h> int main() < int *ptr; int x; ptr = &x; *ptr = 0; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr); *ptr += 5; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr); (*ptr)++; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr);

2 min read C | Pointer Basics | Question 4

Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes. #include <stdio.h> int main() < int arri[] = <1, 2 ,3>; int *ptri = arri; char arrc[] = <1, 2 ,3>; char *ptrc = arrc; printf("sizeof arri[] = %d ", sizeof(arri)); printf("sizeof ptri = %d ", sizeof(ptri)); printf("sizeof arrc[] =

1 min read C | Pointer Basics | Question 6

#include<stdio.h> int main() < int arr[] = <10, 20, 30, 40, 50, 60>; int *ptr1 = arr; int *ptr2 = arr + 5; printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1)); printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); return 0; > Assume that an int variable takes 4 bytes and a

2 min read C | Pointer Basics | Question 7

#include<stdio.h> int main() < int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; >What is the output of above program? (A) Machine dependent (B) 513 (C) 258 (D) Compiler Error Answer: (A) Explanation: Output is 513 in a little endian machine. To understand this output, let integers be sto

1 min read C | Pointer Basics | Question 10

The reason for using pointers in a C program is (A) Pointers allow different functions to share and modify their local variables. (B) To pass large structures so that complete copy of the structure can be avoided. (C) Pointers enable complex “linked\" data structures like linked lists and binary trees. (D) All of the above Answer: (D)Explanation: S

1 min read C | Pointer Basics | Question 11

C/C++ Code #include void f(int *p, int *q) < p = q; *p = 2; >int i = 0, j = 1; int main() < f(&i, &j); printf(\"%d %d", i, j); getchar(); return 0; >(A) 2 2 (B) 2 1 (C) 0 1 (D) 0 2 Answer: (D)Explanation: See below f() with comments for explanation. /* p points to i and q points to j */ void f(int *p, int *q) < p = q; /* p also points to j now */

1 min read C | Pointer Basics | Question 12

Consider this C code to swap two integers and these five statements after it: void swap(int *px, int *py) < *px = *px - *py; *py = *px + *py; *px = *py - *px; >S1: will generate a compilation error S2: may generate a segmentation fault at runtime depending on the arguments passed S3: correctly implements the swap procedure for all input pointers r

1 min read C | Pointer Basics | Question 13

int f(int x, int *py, int **ppz) < int y, z; **ppz += 1; z = **ppz; *py += 2; y = *py; x += 3; return x + y + z; >void main() < int c, *b, **a; c = 4; b = &c; a = &b; printf("%d ", f(c, b, a)); return 0; >(A) 18 (B) 19 (C) 21 (D) 22 Answer: (B) Explanation: Let us understand this line by line /* below line changes value of c to

1 min read C | Pointer Basics | Question 14

Predict the output of following program #include<stdio.h> int main() < int a = 12; void *ptr = (int *)&a; printf("%d", *ptr); getchar(); return 0; >(A) 12 (B) Compiler Error (C) Runt Time Error (D) 0 Answer: (B) Explanation: There is compiler error in line "printf("%d", *ptr);". void * type pointers cannot be de-referenced. We

1 min read Pointer Arithmetics in C with Examples

Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables store the memory address of another variable. It doesn't store any value. Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer arithmetic operations are slightly different from

10 min read Difference between NULL pointer, Null character ('\0') and '0' in C with Examples

NULL Pointer: The integer constant zero(0) has different meanings depending upon it's used. In all cases, it is an integer constant with the value 0, it is just described in different ways. If any pointer is being compared to 0, then this is a check to see if the pointer is a null pointer. This 0 is then referred to as a null pointer constant. The

2 min read Structure Pointer in C

A structure pointer is defined as the pointer which points to the address of the memory block that stores a structure known as the structure pointer. Complex data structures like Linked lists, trees, graphs, etc. are created with the help of structure pointers. The structure pointer tells the address of a structure in memory by pointing the variabl

3 min read C Program For Pointing To Next Higher Value Node In A Linked List With An Arbitrary Pointer

Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node whi

5 min read When do we pass arguments by pointer?

In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following cases: 1. To Modify Local Variables of the Function

5 min read A C/C++ Pointer Puzzle

Prerequisite: Pointers Assuming the size of int = 4 bytes, size of a pointer variable = 8 byte, what will be the output of following program. Few hints on how to solve it: Size of int = 4 bytes, size of a pointer variable = 8 bytes (on my machine), adding 1 to a pointer makes the pointer point to its next immediate type a is of type int (*)[5][6] a

2 min read void Pointer in C

A void pointer is a pointer that has no associated data type with it. A void pointer can hold an address of any type and can be typecasted to any type. Example of Void Pointer in C C/C++ Code // C Program to demonstrate that a void pointer // can hold the address of any type-castable type #include <stdio.h> int main() < int a = 10; char b = '

3 min read How to Declare a Pointer to a Struct in C?

Structure (or structs) in the C programming language provides a way to combine variables of several data types under one name and pointers provide a means of storing memory addresses. In this article, we will learn how to declare such a pointer to a struct in C. Declaration of Pointer to Struct in CTo declare a pointer to a struct we can use the st

2 min read How to Modify Struct Members Using a Pointer in C?

In C++, we use structure to group multiple different types of variables inside a single type. These different variables are called the members of structures. In this article, we will discuss how to modify the struct member using a pointer in C. Example Input: myStruct.mem1 = 10; myStruct.mem2 = 'a'; Output: myStruct.mem1 = 28; myStruct.mem2 = 'z';