Originally Posted by
_Mike
@OP:
Try this code
Code:
#include<stdio.h>
int* get_local_var(int i)
{
int ret = i;
return &ret;
}
int main()
{
int* i1 = get_local_var(1);
int* i2 = get_local_var(2);
printf("i1: %d\n", *i1);
return 0;
}
i1 should print 1, right?
ret is a local variable, you can't pass its address because it's gone when get_local goes out of scope. If you want to return local variable, return by value.
Code:
int get_local_var(int i)
{
int ret = i;
// do somethign else to ret here
return ret;
}
Unless you allocate the memory on the heap, then yes, you can return the pointer. But that is a pretty bad practice becuase you will forget to free it later.
Code:
int * get_local_var(int i)
{
int* ret=malloc(sizeof (int));
*p=i;
return p; <-------- have to free this in main() or whereever. When you have a hundred of these pointers, it becomes impossible to keep track of them.
}