Davey
Davey

Reputation: 446

Sending a pointer from a function

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

Answers (3)

Tio Pepe
Tio Pepe

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

yaman
yaman

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

Naveen
Naveen

Reputation: 73473

When the first function ends the variable is destroyed, hence the pointer becomes invalid.

Upvotes: 1

Related Questions