如何使用C中的空指针? [英] How do you use the void pointer in C?

查看:125
本文介绍了如何使用C中的空指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是几个说我无法理解如何完成函数声明。我已经扫描的网页看到一个空指针是什么,我明白,它必须强制转换的东西是有用的(因为它只是指出了一些内存块),但我没有看到在完成这些如何帮助声明。

Here are a couple of function declarations that I'm having trouble understanding how to complete. I've scanned the web to see what a void pointer is, and I understand that it must be cast to something to be useful (because it just points to some memory block), but I don't see how that helps in completing these declarations.

/* type of comparison function that specifies a unique order.
   Returns 1 if pointer1 should come before,
   0 if equal to, or -1 if after pointer2. */
typedef int (*compare_function) (const void* pointer1, const void* pointer2);

/* get the data object */
void* get_obj(const void* item_pointer);

有更多类似的功能,但我想如果我知道如何做到这两个,我应该在良好的状态。例如,对于第二个函数,我们怎么投的item_pointer到合适的东西应该归还?

There are more functions like this, but I think if I understand how to do these two I should be in good shape. For example, for the second function, how do we cast the item_pointer to anything appropriate that should be returned?

推荐答案

无效* 通常意味着你只是在考虑其类型的数据的地址有兴趣,一些原因:

void * usually means that you are only interested in the address of the data regardless of its type, some of the reasons:


  • 数据这无效* 指向是隐藏的,你不应该直接访问数据的 信息隐藏,你的函数2是正确的这种情况的一个例子。

  • the internal representation of the data this void * pointing to is hidden, you are not supposed to access the data directly, information hiding, your function 2 is properly an example of this case.

类型由一些函数称为调用链,就像的qsort 和参数传递给其他函数的大部分功能。

the type is known by some function in the call chain, like with qsort and most functions that pass arguments to other functions.

不需要型,因为该指针指向将不同类型与的memcpy 其可以处理的数据作为字节进行处理,如数据, 无符号字符*

the type is not required because the data the pointer is pointing to will be handled as different type, like with memcpy which may handle the data as bytes, unsigned char *.

这篇关于如何使用C中的空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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