kernel.lover said:
hello,
I want to know if a fuction say malloc is declared as void *malloc()
then whats the significance of void here.
`void*' is a data type, just like `int' or `double'.
It happens to be a pointer type, like `char*', but with
a special property that no other data pointer has: you
can convert any legitimate data pointer value to `void*'
and back again without loss of information and without
a cast or any such shenanigans.
This means that `void*' is useful as a "pointer to
anything," or more exactly as a pointer to some data object
whose type is irrelevant at the moment. malloc() cannot
know what data type you intend to store in the allocated
memory, but it doesn't need to: All it needs to know is how
many bytes you require. It finds the bytes and returns you
a pointer to them -- but what kind of pointer should it be?
`char*'? `double*'? `struct something_new_under_the_sun*'?
malloc() doesn't know your intent, so it returns `void*',
the "anything" pointer type.
You can't do very much with the `void*' pointer in its
original form as returned by malloc(), but you can easily
convert it to a pointer to the actual type you want to store:
just write `char *ptr = malloc(42);' or some such. You will
encounter code like `char *ptr = (char*)malloc(42);' but the
cast is unnecessary: when you see such things, you can guess
that they were written by someone whose understanding of
pointers may be uncertain, or by someone who learned his C in
the pre-Standard days when `void*' didn't exist, or by someone
who writes a lot of C++ (the C++ rules are different).
Going the other way, there are functions that operate
on data objects without caring about their type: fwrite(),
for example, doesn't care whether the bytes it writes came
from a `long double' or from an array of `unsigned short'. So
fwrite() accepts a `void*' argument to point to the data; you
can pass it any kind of data pointer and it will silently and
automatically convert to `void*':
long double down_the_left_field_line = 42.0;
fwrite (&down_the_left_field_line, /* etc */);
> Does void * is used when function has the flexibility to return any
> type of value by casting that functions with appropriate data type?
Almost. `void*' can carry any data pointer value, but
not "any type of value" -- a `void*' can carry a `double*'
value, but not a `double' value. Also, `void*' converts to
and from any data pointer type automatically, without any cast
required.