memory allocation in subroutine

Hi everyone,

I'm not new to C programming, but I'm having question regarding the memory allocation of a pointer variable which, for instance, will be declared in main(), but its memory will be allocated in subroutine.

To clearify my question, I provide a small working example:

#include <stdlib.h>

void subroutine(void **ptr);

main()
{
  void **ptr  = NULL;
 
  subroutine(&ptr);

  return 0;
}

void subroutine(void **ptr)
{
   *ptr = (void*) malloc (10);
}

Why do I have to declare that variable as a pointer to a pointer?
Can someone explain that example to me? Why I can't simply pass the address of "ptr" to the subroutine by "subroutine(ptr);". Why do I have to apply an additional address operator? What is the result of "&ptr", because I thought "ptr" is already the address.

That is not resonable to me.

From my understanding that is what I would have done:

#include <stdlib.h>

void subroutine(void *ptr);

main()
{
  void *ptr  = NULL;
 
  subroutine(ptr);

  return 0;
}

void subroutine(void *ptr)
{
   ptr = (void*) malloc (10);
}

Thanks for your help!

Regards,
Maik

The problem with your latter version is that the variable in main() won't be modified at all. In the subroutine, only the ptr local to the subroutine will be modified. To allow the ptr in main() to be modified, you are required to take a pointer to that variable, and thus requiring '&' on the calling side and an additional '' on the callee side. This is true regardless of the type of the variable. It just happens that the type this time is void. If the variable is an "int", then the parameter in the subroutine signature will be "int*".

One thing you need to keep in mind, is that parameters are passed by value.