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.
The below program will give segmentation fault since ‘A’ was local to the function:
Below is the output of the above program:
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.
- Double Pointer (Pointer to Pointer) in C
- Pointer to an Array | Array Pointer
- What is a Pointer to a Null pointer
- How can I return multiple values from a function?
- C function argument and return values
- How to return multiple values from a function in C or C++?
- How to declare a pointer to a function?
- Function Pointer in C
- return statement vs exit() in main()
- Implicit return type int in C
- Pointer vs Array in C
- void pointer in C / C++
- NULL pointer in C
- C | Pointer Basics | Question 1
- C | Pointer Basics | Question 2
- C | Pointer Basics | Question 3
- C | Pointer Basics | Question 4
- C | Pointer Basics | Question 6
- C | Pointer Basics | Question 7
- C | Pointer Basics | Question 10
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.