如何遍历数组参数作为空指针 [英] How to traverse an array parameter as void pointer

查看:138
本文介绍了如何遍历数组参数作为空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似qsort的通用"过程,它具有一个void指针(指向一个数组)和一个函数指针参数.此函数应可在任何类型的数组上使用.

I have similar "generic" procedure like qsort, which has a void pointer (pointing at an array) and also a function pointer parameter. This function should work on any type of array.

示例:

void do_something(void * array, int count, int size, void (*test)(const void*)){
    int i;
    for(i=0; i<count; i++){
        test(array + (index * size));
    }
}

但这给了我以下警告(gcc test.c -pedantic-errors):

This however gives me the following warning (gcc test.c -pedantic-errors):

error: pointer of type ‘void *’ used in arithmetic [-Wpedantic]

经过一些研究,我发现使用像这样的void指针是一种不好的做法. (例如 C中空指针的指针算法)

And after some research I found out it's a bad practice to use void pointers like this. (E.g. Pointer arithmetic for void pointer in C)

那么标准库如何为qsort这样的东西呢?查看此代码:( http://aturing. umcs.maine.edu/~sudarshan.chawathe/200801/capstone/n/qsort.c ),我看到了以下内容:

So how does the standard library do this kind of stuff for like qsort? Looking at this code: (http://aturing.umcs.maine.edu/~sudarshan.chawathe/200801/capstone/n/qsort.c), I see the following:

void
_quicksort (void *const pbase, size_t total_elems, size_t size,
        __compar_fn_t cmp)
{
  register char *base_ptr = (char *) pbase;
  ....
  char *lo = base_ptr;
  char *hi = &lo[size * (total_elems - 1)];
  ...
}

无论实际类型如何,它们都转换为(char *)吗?

Are they casting to (char *) regardless of the actual type?

推荐答案

我问了类似的问题无效*算术未定义.向void指针加1是什么意思?大多数编译器(如果允许)将其视为按sizeof(char)(下一个字节")递增,但警告您.

Void * arithmetic is not defined. What does it mean to add 1 to a void pointer ? Most compilers (if they allow it) treat it as incrementing by sizeof(char) ("the next byte") but warn you.

所以正确的做法是显式地使其执行您想要的操作->强制转换为char *并递增该值

So the right thing to do is to explicitly make it do what you want -> cast to char* and increment that

这篇关于如何遍历数组参数作为空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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