你如何在C中使用void指针?

Bob*_*son 3 c c++ pointers

这里有几个函数声明,我无法理解如何完成.我已经扫描了网络以查看无效指针是什么,我理解它必须被转换为有用的东西(因为它只指向一些内存块),但我不知道这对于完成这些有什么帮助声明.

/* 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);
Run Code Online (Sandbox Code Playgroud)

有更多这样的功能,但我想如果我理解如何做这两个我应该保持良好状态.例如,对于第二个函数,我们如何将item_pointer转换为应该返回的任何适当的东西?

小智 9

void * 通常意味着您只对数据的地址感兴趣,无论其类型如何,其中一些原因如下:

  • 这个void *指向隐藏的数据的内部表示,你不应该直接访问数据,信息隐藏,你的功能2恰恰是这种情况的一个例子.

  • 该类型由调用链中的某个函数知道,就像使用qsort和大多数将参数传递给其他函数的函数一样.

  • 该类型不是必需的,因为指针指向的数据将被处理为不同的类型,例如memcpy可以将数据作为字节处理unsigned char *.