why calloc pointer type is void *? [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

This question already has an answer here:

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!

回答1:

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().



回答2:

calloc returns void* since:

  1. calloc can be used to allocate memory for any type of object.
  2. a void* can be implicitly cast to other pointer types.

If you use:

void* ptr = calloc(...); 

it is valid but you can't use *ptr. A void* is not dereferenceable The pointer has to be cast to some other type to be dereferenced. E.g.

char* cptr = ptr; *cptr = 'a'; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!