且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是无效*含义及如何使用它?

更新时间:2022-05-22 15:15:29

一个指针无效是一个通用指针类型。 A 无效* 可以转换为任何其他指针类型没有一个明确的转换。你无法取消引用无效* 或用它做指针算法;必须将其转换为一个指向完整的内容型第一。

A pointer to void is a "generic" pointer type. A void * can be converted to any other pointer type without an explicit cast. You cannot dereference a void * or do pointer arithmetic with it; you must convert it to a pointer to an complete data type first.

它得到在您需要能够在同一code。与不同的指针类型的工作场所。一个普遍引用的例子是库函数的qsort

It gets used in places where you need to be able to work with different pointer types in the same code. One commonly cited example is the library function qsort:

void qsort(void *base, size_t nmemb, size_t size, 
           int (*compar)(const void *, const void *));

是一个数组的地址, nmemb个是数组中元素的个数,大小是每个元件的尺寸和 COMPAR 是指向用于比较阵列的两个元素的功能。它被调用,像这样:

base is the address of an array, nmemb is the number of elements in the array, size is the size of each element, and compar is a pointer to a function that compares two elements of the array. It gets called like so:

int iArr[10];
double dArr[30];
long lArr[50];
...
qsort(iArr, sizeof iArr/sizeof iArr[0], sizeof iArr[0], compareInt);
qsort(dArr, sizeof dArr/sizeof dArr[0], sizeof dArr[0], compareDouble);
qsort(lArr, sizeof lArr/sizeof lArr[0], sizeof lArr[0], compareLong);

数组前pressions IARR dArr lArr 被隐式地从数组类型转换为指针类型的函数调用,每间隐含的指针转换为 INT / / 到指针无效

The array expressions iArr, dArr, and lArr are implicitly converted from array types to pointer types in the function call, and each is implicitly converted from "pointer to int/double/long" to "pointer to void".

比较函数看起来是这样的:

The comparison functions would look something like:

int compareInt(const void *lhs, const void *rhs)
{
  const int *x = lhs;  // convert void * to int * by assignment
  const int *y = rhs;

  if (*x > *y) return 1;
  if (*x == *y) return 0;
  return -1;
}

通过接受无效* 的qsort 可以与任何类型的数组。

By accepting void *, qsort can work with arrays of any type.

使用的缺点无效* 是你扔的类型安全窗外,迎面而来的流量。没有什么可以保护你使用了错误的比较例程:

The disadvantage of using void * is that you throw type safety out the window and into oncoming traffic. There's nothing to protect you from using the wrong comparison routine:

qsort(dArr, sizeof dArr/sizeof dArr[0], sizeof dArr[0], compareInt);

compareInt 期待它的参数是指向 INT S,但实际上是与双秒。有没有办法赶上在编译时这个问题;你只是风与一个错误排序的数组。

compareInt is expecting its arguments to be pointing to ints, but is actually working with doubles. There's no way to catch this problem at compile time; you'll just wind up with a mis-sorted array.