📍📚Intermediate
Return a Pointer from a Function
Function returning pointer
A function can return a pointer to dynamically allocated memory or to static/global variables. Be careful not to return pointers to local variables!
C Program Returning a Pointer
return_pointer.c
C
1#include <stdio.h>2#include <stdlib.h>34// Function returning pointer to dynamic array5int* createArray(int n) {6 int *arr = (int*)malloc(n * sizeof(int));7 8 for (int i = 0; i < n; i++) {9 arr[i] = (i + 1) * 10; // 10, 20, 30...10 }11 12 return arr; // Return pointer13}1415int main() {16 int n = 5;17 int *myArray = createArray(n);18 19 printf("Array elements: ");20 for (int i = 0; i < n; i++) {21 printf("%d ", myArray[i]);22 }23 printf("\n");24 25 free(myArray); // Don't forget to free!26 27 return 0;28}Output
Array elements: 10 20 30 40 50
⚠️ Common Mistake
Never return a pointer to a local variable! Local variables are destroyed when the function returns, leaving a dangling pointer.
🎯 Key Takeaways
✓Return pointers to heap memory (malloc)
✓Or return pointers to static variables
✓Never return pointer to local variable
✓Always free() dynamically allocated memory
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials