chandan said:
In my case, i was trying to compile this code with a C++ compiler.
That's always a mistake. You wouldn't try to compile Algol with a Pascal
compiler, so why compile C with a C++ compiler?
But,
please, can you elaborate how it masks the error and how stdlib.h helps
It provides a full prototype for calloc, thus telling the compiler that
malloc returns void *.
in conversion of type void * to target pointer type?
By telling the compiler that calloc returns void *, the prototype assists in
the generation of correct code. Without the prototype, the compiler would
be forced to assume that calloc returns int (which calloc doesn't in fact
return).
In the following example, I use malloc rather than calloc, for the simple
reason that experienced C programmers hardly ever use calloc as its side
effect is generally (but not quite always) unnecessary, but the reasoning
is identical.
i mean, how it
determines the target pointer type, if i am using a C compiler.
#include <stdio.h> /* for printf prototype */
#include <stdlib.h> /* for malloc prototype */
typedef int T; /* any object type will do here */
int main(void)
{
T *p; /* compiler now knows p has type T *, so all is well */
size_t n = 42; /* compiler now knows n has type size_t, so all is well */
p = malloc(n * sizeof *p); /* malloc returns void *, and the compiler
* knows that p has type T *, and the
* compiler knows how to convert
* between void * and T *, so there is
* no problem here. */
if(p != NULL)
{
printf("Yes, I got the memory. It's at %p.\n", (void *)p);
free(p);
}
return 0;
}