I have to implement a wrapper for malloc called mymalloc with the following signature:
void mymalloc(int size, void ** ptr)
Is the void** needed so that no type casting will be needed in the main program and the ownership of the correct pointer (without type cast) remains in main().
void mymalloc(int size, void ** ptr)
{
*ptr = malloc(size) ;
}
main()
{
int *x;
mymalloc(4,&x); // do we need to type-cast it again?
// How does the pointer mechanism work here?
}
Now, will the pointer being passed need to be type-cast again, or will it get type-cast implicitly?
I do not understand how this works.
mallocreturns avoid*. For your function, the user is expected to create their own, localvoid*variable first, and give you a pointer to it; your function is then expected to populate that variable. Hence you have an extra pointer in the signature, a dereference in your function, and an address-of operator in the client code.The archetypal pattern is this:
For your usage example, substitute
T = void *, and the fruits of your labour are the results ofmalloc(plus checking).However, note that an
int*isn’t the same as avoid*, so you cannot just pass the address ofxoff as the address of a void pointer. Instead, you need: