antil antil - 1 month ago 8
C Question

why calloc pointer type is void *?

I reading a C book. but can't understand sentence that is

If the call calloc is successful, pointer of type void* that points to the base of the array in memory is returned;

Here, if pointer of type void* that points to the base of the array in memory, then array[0] has type of void??

I want know what is mean...

Thank you guys read my question I hope receive answer!

Answer

I can see how it's tempting to think that since int * points to int, then void * should point to void. But that's not the case. There's really no useful relationship between void * and void so it's best to think of them as separate concepts.

void * in C means a pointer that points to an object of unspecified type. You can think of it as the C analogue of Java Object if you're familiar with that.

void * has the following properties:

  • Any pointer type can be converted to and from void *, i.e. void * is large enough to hold any pointer, even on machines where pointers to different types can have different size.

  • Conversion between void * and other pointer types is implicit, you don't have to do an explicit cast.

  • It's not permitted to de-reference void *, i.e. we must cast it to a concrete pointer type before accessing the memory it points to.

  • You can't do address arithmetic on a void * in Standard C, though GCC allows you to do it as a documented extension.

void * is the type of choice for a function that needs to handle arbitrary data, like calloc().