Search code examples
cpointersdouble-pointer

simple pointers to pointers


I know why this works:

#include <stdio.h>

void cool_number(int **number) {
  int value = 42;
  int *p = &value;
  *number = p;
}

int main () {
  int *number;
  cool_number(&number);
  printf("number is %d\n", *number);
  return 0;
}

What I don't understand is why this doesn't (in my machine it prints 3700 or something like that).

#include <stdio.h>

void cool_number(int **number) {
  int value = 42;
  int *p = &value;
  int **x = &p;
  number = x;
}

int main () {
  int *number;
  cool_number(&number);
  printf("number is %d\n", *number);
  return 0;
}

Why aren't both equivalent?


Solution

  • I assume they're not equivalent because number is passed by value, on the stack, as is standard for function parameters. Any changes that you make directly to number inside of cool_number() are modifying the local copy on the stack, and are not reflected in the value of number in main().

    You get around this in the first example by dereferencing number, which tells the computer to modify some specific location in memory that you also happen to have a pointer to back in main(). You don't have this in the second example, so all that happens is that you make the local number pointer point to somewhere else, without actually updating any memory location being referred to back in main(). Thus nothing you do shows up once you get back to main().

    And since value is local to the cool_number() function, setting a reference to it that will be accessed after cool_number() returns isn't guaranteed to work and certainly shouldn't be used in any code outside of a trivial/toy example. But in this specific instance it's not really related to why you're seeing different results between the two pieces of code.