Understanding pass pointer to pointer by reference in c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void func(char *ptr)        //Passed by      reference
{
  *ptr = 'B';
}

int main()
{
  char *ptr;
  ptr = (char *) malloc(sizeof(char) * 1);
  *ptr = 'A';
  printf("%c\n", *ptr);

  func(ptr);
  printf("%c\n", *ptr);
}

I was confuse I know that ptr=(char*)malloc (sizeof(char*1) here means allocate 1 byte and return a pointer to the allocation then assign to ptr, so ptr is a pointer.

But when it calls func(ptr) why it not use &? Although what I want is to change the character inside ptr points to? Why not using void func(char** ptr) and send func(&ptr) here? Is it possible?

I mean what made this pass by reference and not by value?
Why this not pass copy of the pointer?
Is this mean in func(ptr), i pass pointer which is memory address(malloc) and was define as char*ptr in func?? So thats why it work?

The pointer is passed by value. The function doesn't modify the pointer, it modifies the character that the pointer points to.
Topic archived. No new replies allowed.