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