incompatible pointer type warning
17,298
Solution 1
#include <stdio.h>
#include <stdlib.h>
int myAlloc(void *ptr,int size)
{
*(void **)ptr=malloc(size);
if(!ptr) return 0;
else return 1;
}
int main()
{
int *p=NULL;
myAlloc(&p,sizeof(int));
*p=5;
printf("%d\n",*p);
return 1;
}
Solution 2
your function, myMalloc
takes a pointer to a pointer to void, or void**
you are passing it the address of a pointer to an int, or int**
You need to cast the pointer you pass to be void eg
myAlloc((void**)&p,sizeof(int));
Author by
user995487
Updated on June 04, 2022Comments
-
user995487 almost 2 years
I have a C program like the one below. I am trying to write a wrapper on top of
malloc
with the signatureint myAlloc()
. This wrapper should return 1 on a successful memory allocation or return 0 if memory allocation fails.#include <stdio.h> #include <stdlib.h> int myAlloc(void **ptr, int size) { *ptr = malloc(size); if (!ptr) return 0; else return 1; } void main() { int *p = NULL; myAlloc(&p, sizeof(int)); printf("%d\n", *p); }
When I compile this I get a warning saying "incompatible pointer type". How can I make it possible for this function to be called with any possible pointer type without receiving the warning?
Is it possible to remove the casting operation from the actual function call?
Update
I found the answer. Here is corrected code:
#include <stdio.h> #include <stdlib.h> int myAlloc(void *ptr,int size) { *(void **)ptr = malloc(size); if (!ptr) return 0; else return 1; } int main() { int *p = NULL; myAlloc(&p, sizeof(int)); *p = 5; printf("%d\n", *p); return 1; }