c - Trying to return an address of a local variable in a function -
i want homecoming address of variable k in function func(). here 2 functions.
main() function
#include <stdio.h> main() { int* j; int* func(); j= func(); printf("\n%d",*j); }
func() function
int* func() { static int k=30; homecoming (&k); } i wanted int *func() homecoming address of k, next error displayed.
function returns address of local variable [-wreturn-local-addr]
return (&k);
k local variable exists within function func. returning address k not exist. undefined behavior.
you allocate dynamic memory k:
int *k = (int*)malloc(sizeof(int)); *k = 30 homecoming k; do not forget free memory in main
free(j); c function pointers
No comments:
Post a Comment