C Void Pointer

C语言中的void*指针是一种通用指针类型,可以转换为任何其他指针类型而无需显式类型转换。它常用于函数如`qsort`,允许对不同类型的数组进行排序。然而,使用void*会牺牲类型安全,可能导致运行时错误,例如当传递错误的比较函数时。在使用void*时,需要特别注意类型匹配,以防止潜在的编程错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from c - What does void* mean and how to use it? - Stack Overflow

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 a complete data type first.

void * is often 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 *));

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);

The array expressions iArrdArr, 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;
}

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 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 missorted array.

  • It's actually not guaranteed that a void* can be cast to a function pointer. But for data pointers what you said holds. 

    – Vatine

     Jul 12 '16 at 10:52
  • Before void pointers were available "char *" was used instead. But void is better as it cannot actually be used to alter anything directly

    – user50619

     Jun 4 '19 at 13:08
指针运算(Pointer Arithmetic)是C语言中非常重要的特性之一,允许程序员对指针进行算术操作。主要包括加法、减法以及比较等基本操作,这些操作使得能够方便地访问数组元素或是动态分配的内存块内的各个位置。 ### 指针的基本概念回顾 在讨论指针运算之前,先简短复习一下关于指针的基础知识: - **声明**: 定义一个指向特定类型数据项的指针变量。 ```c int *p; // 声明了一个指向整型(int) 的指针p char *q; // 声明了一个指向字符(char) 的指针q ``` - **初始化和赋值**: 把某个现有对象地址存储到指针当中去 ```c int a = 5; p = &a; // 将a 变量的位置存入了指针p 中 ``` - **解引用**: 获取当前由该指针对应的实际内容(即“间接寻址”) ```c printf("%d\n", *p); // 输出通过*p 得来的实际数值, 即变量a 内容 ``` --- ### 指针算术的应用场景及规则 #### 加法与自增(+ 和++) 当你向指针添加正值时,它会根据其所指向的数据类型大小自动递增相应的字节数,并移动至下一个合适偏移处继续表示有效的新地址。 假设我们有一个整数类型的数组arr[], 并创建相应的一个int 类型的指针ptr 来跟踪其中每个成员的变化过程: ```c int arr[] = {10, 20, 30}; int *ptr; // 初始化 ptr 到第一个元素地址上 ptr = arr; // 或者也可以写作: ptr=&arr[0]; printf("Value at location %p is %d.\n", (void *)ptr , *ptr ); ptr++; // 相对于原来增加了 sizeof(int)=4 Bytes (一般而言) printf("After incrementing pointer Value at location %p is %d .\n",(void *)ptr,*ptr); ``` 以上例子展示了如何利用简单的加法规则遍历整个一维线性表结构里的所有项目! ##### 减法规律(-) 相似地,如果从现有的某指定点开始减少距离,则同样依据基础单元尺寸决定最终返回的新目标坐标是否合法合理范围内即可完成预期功能任务. 再次回到刚才提到过的那个同样的整型数组样本... ```c ptr -=2 ; // 返回两格前的那个地方也就是第二个元素那里... printf("Decremented twice now points to second element whose value=%d \n ",*ptr ); ``` 注意这里要注意越界可能性问题哦~ 因为我们已经回到了比初始起点还要往前的状态啦! 最后就是两者之间差了多少个单位长度的问题解答咯~ ```c ptrdiff_t diff= ptr -&arr[0]; printf ("There are %td elements between them.",diff ); ``` 此表达式计算出了从原始首端直至目前所在为止经过了多少次跳跃跨越而成的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值