void * 分配给 void **

void * assignment to void **

需要实现一个api,它有一些参数;它有输入的类型(const void*),输出的类型(void**); api 想要将带有一些偏移量的输入分配给输出;例如,

void getOffset(const void* a, void** b)
{
    int offset = getsomeoffset();
    *b = a + offset; 
} 

这在编译器中会有一些抱怨。编写此代码的正确方法是什么?输入的类型可以是 float、int、double。

您不能在 void * 指针上应用指针算术。指向的目标没有任何类型,因此没有可用于计算偏移量的大小。

因此您需要在应用偏移量之前转换您的指针:

*b = ((char *)a) + offset; 

对于此语句,偏移量被解释为字节数。

这里的问题是偏移量。 void 没有大小,因此 C 不允许在 void * 上进行指针运算。假设你想使用字节地址,你应该通过 char * 算法:

void getOffset(const void* a, void** b)
{
    int offset = getsomeoffset();
    char *p = a;   // automatic conversion from void * to char *
    p += offset;   // char pointer arithmetics
    *b = p;        // automatic conversion for char * to void *
    // or directly:        *b = ((char *) a) + offset; 
}

鉴于 void *aa + offset 违反了 6.5.6 Additive operators, paragraph 8 of the C standard

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough...

A void * 没有类型,也不能指向实际对象。

正如其他人指出的那样,您必须将 void * 转换为另一种类型,很可能 char * 是合适的。