How to Return Pointer from Function in C: Syntax and Examples
In C, you can return a pointer from a function by specifying the return type as a pointer type, for example
int *. The function returns the address of a variable or dynamically allocated memory, allowing the caller to access or modify the data via the pointer.Syntax
To return a pointer from a function, declare the function's return type as a pointer type. For example, int *functionName() means the function returns a pointer to an integer.
- Return type: Pointer type like
int *,char *, etc. - Function name: Your chosen function name.
- Return statement: Return the address of a variable or dynamically allocated memory.
c
int *functionName(); int *functionName() { int *ptr; // assign ptr to point to some int return ptr; }
Example
This example shows a function that returns a pointer to a static integer variable. The main function prints the value using the returned pointer.
c
#include <stdio.h> int *getPointer() { static int value = 42; // static to keep value valid after function ends return &value; } int main() { int *ptr = getPointer(); printf("Value pointed to: %d\n", *ptr); return 0; }
Output
Value pointed to: 42
Common Pitfalls
Returning a pointer to a local (non-static) variable is a common mistake because the variable's memory is freed when the function ends, leading to undefined behavior.
Always return pointers to static variables, dynamically allocated memory, or variables passed by reference.
c
/* Wrong: returning pointer to local variable */ int *wrong() { int local = 10; return &local; // local is destroyed after function ends } /* Correct: returning pointer to static variable */ int *correct() { static int value = 10; return &value; }
Quick Reference
| Concept | Description |
|---|---|
| Function return type | Declare as pointer type (e.g., int *) |
| Return value | Return address of static/dynamic variable |
| Avoid | Do not return pointer to local non-static variable |
| Use case | Access or modify data outside function scope |
Key Takeaways
Declare the function return type as a pointer to return a pointer.
Return pointers to static or dynamically allocated variables to keep them valid.
Never return pointers to local non-static variables as they become invalid.
Use the returned pointer to access or modify data outside the function.
Static variables inside functions retain their value and address after function ends.