Confused by a question in the quiz

#include<stdio.h>
 
void f(int *p) {
  int b = 2;
  p = &b;
  printf("%d ", *p);
}
 
int main() {
  int a = 1;
  int *p = &a;
  f(p);
  printf("%d ", *p);
}

The anwser should be 2 1.
Why isn’t the second output be 2 instead of 1?

I don’t know C, but I’ve been learning bits of C++.
I think its a pass by value vs. pass by reference issue.

What you have does “pass by value” for the function, so you get a copy of the original pointer as p in the function
so you’re changing a copy of the pointer, not the original pointer (which stays the same)

To change it to be “pass by reference”, I guess you would do

void f(int *&p) {

so that it changes the original pointer, not just a copy of it.

#include<stdio.h> void f(int *p) { int b = 2; p = &b; printf("%d ", *p); } void g(int *&p) { int b = 2; p = &b; printf("%d ", *p); } int main() { int a = 1; int *p = &a; f(p); printf("%d ", *p); printf("\n"); g(p); printf("%d ", *p); }