可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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:
calloc
can be used to allocate memory for any type of object. - 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';