C Tutorial
Like function return int, float, char, or any other data type, function can also return a pointer.
To return a pointer in function, needs to be explicitly mentioned in the calling function and also in function definition.
This C program returns a pointer of local integer variable in the function but local variable (val) scope dies in calling function, so prints nothing.
#include <stdio.h> // Function declaration. int *get_addr(); void main() { int *addr; addr = get_addr(); printf("%u\n", addr); printf("%d\n", *addr); } // Function returning a pointer int *get_addr() { int val = 10; return &val; }Output:
$ cc function-return-pointers.c function-return-pointers.c: In function ‘get_addr’: function-return-pointers.c:16:10: warning: function returns address of local variable [-Wreturn-local-addr] return &val; ^~~~ $ ./a.out 0 Segmentation fault (core dumped)
Make static to prevent val to be survived,
#include <stdio.h> // Function declaration. int *get_addr(); void main() { int *addr; addr = get_addr(); printf("%u\n", addr); printf("%d\n", *addr); } // Function returning a pointer int *get_addr() { static int val = 10; return &val; }Output:
$ cc function-return-pointers.c $ ./a.out 6295596 10
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page