Reputation: 446
This is just something I was wondering. Well here goes, Say I declare a variable in a function, I pass this variable as a pointer to another function. What happens with this variable when the first function (where the variable is declared) ends? Does it stay on the stack or does it get removed when the function ends?
Thanks in advance =D
Upvotes: 0
Views: 97
Reputation: 3089
If you declared this variable on stack it will disapear:
void foo()
{
int varInStack;
foo2(&varInStack);
// when foo returns, you loosed your variable.
}
You may return it:
int foo()
{
int varInStack;
foo2(&varInStack);
return varInStack;
}
Upvotes: 1
Reputation: 769
When the function you define a variable returns the variable is destroyed, unless you declared it static. Check storage classes in C. Here is a pointer: http://aelinik.free.fr/c/ch14.htm
Upvotes: 4
Reputation: 73473
When the first function ends the variable is destroyed, hence the pointer becomes invalid.
Upvotes: 1