2
void func(char *p)
{
    int q = 13;
    p = &q;
    printf("%d\n", *p);
}

void main(void)
{
    int var = 20;
    int *p = &var;

    printf("%d\n", *p);

    func(p);

    printf("%d\n", *p);
}

How come at the function exit the pointer is still 20? I was hopping when the func() ends, the pointer is modified in it, in the last printf(), the *p value would be pointing some random stuff from the stack.

Theo P.
  • 21
  • 2

2 Answers2

6

What you had is this

void func(char *p)
{
    int q = 13;
    p = &q;
}

This means "make p point to q" and changes value of p, which is just a variable inside the function. No variable value changes are reflected outside the function.

If you were to write this

void func(char *p)
{
    int q = 13;
    *p = q;
}

This would mean "make the variable to which p points to change its value to 13" and that would be seen outside, meaning the variable var in main would change its value (depends on endianness what it would be since it's int and not char as the pointer claims it to be).

If you want to change the pointer's value in main you need a double pointer:

void func(char **p)
{
    int q = 13;
    *p = &q;
    printf("%d\n", *p);
}

This would mean "make the pointer to which p points to point to a local variable q" and in this case you would have a dangling pointer as you expected in main.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
  • `void func(char **p) { int q = 13; *p = &q; ... ` will invoke undefined behavior if the pointer is dereferenced after the call to `func()`. – Andrew Henle Mar 26 '19 at 10:54
3

No, p itself is passed be value. Any change made to p inside func() will not be reflected back to main().

For sake of completeness, any changes made to the value pointed to by p (i.e., *p) would have been reflected back in main().

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261