为什么calloc指针类型为void *? [英] why calloc pointer type is void *?

查看:132
本文介绍了为什么calloc指针类型为void *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本C书。但是无法理解这样的语句



如果调用calloc成功,则返回void *类型的指针,该指针指向内存中数组的基址; p>

这里,如果类型为void *的指针指向内存中数组的基址,则array [0]的类型为void ??



我想知道这是什么意思...



谢谢大家阅读我的问题,希望得到答案!

解决方案

由于 int * 指向 int ,然后 void * 应该指向 void 。但是事实并非如此。 void * void 之间确实没有任何有用的关系,因此最好将它们视为独立的概念。

C中的

void * 表示指向未指定类型的对象的指针。如果您熟悉它,可以将其视为Java Object 的C类似物。



void * 具有以下属性:




  • 任何指针类型都可以转换为从 void * 开始,即 void * 足够大,可以容纳任何指针,即使在指向不同类型的指针的机器上可以具有不同的大小。


  • void * 与其他指针类型之间的转换是隐式的,您不必


  • 不允许取消引用 void * ,即在访问指向它的内存之前,必须将其转换为具体的指针类型。


  • 您不能对进行地址算术运算无效* 在标准C中,尽管GCC允许您将其作为文档扩展名进行。




void * 是需要处理任意数据的函数的选择类型,例如 calloc ()


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!

解决方案

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

这篇关于为什么calloc指针类型为void *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆