-1

Need to implement one api which has some parameters;which has input's type (const void*), output's type (void**); the api wants to assign input with some offset to the output; for example,

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

This will have some complain in the compiler. What's the correct way to write this code? The input's type can be float, int, double.

yewei
  • 241
  • 2
  • 9
  • If your compiler complains, please always include the warning or error in your questions – Gerhardh Dec 10 '18 at 11:17
  • 1
    Arithmetic on a void pointer violates the C standard. See https://stackoverflow.com/questions/3523145/pointer-arithmetic-for-void-pointer-in-c – Andrew Henle Dec 10 '18 at 11:17
  • This function seems completely redundant in the first place. I'd stop and consider if the program design makes sense at all. – Lundin Dec 10 '18 at 11:44

3 Answers3

4

You cannot apply pointer arithmetics on a void * pointer. The target pointed to does not have any type and hence no size which could be used to calculate the offset.

Therefore you need to cast your pointer before applying the offset:

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

With this statement the offset is interpreted as number of bytes.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
0

The problem here is the offset. A void has no size, so C does not allow pointer arithmetics on void *. Assuming that you want to use byte addresses, you should pass through char * arithmetics:

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; 
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

Given void *a, a + offset violates 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 * doesn't have a type, and it can't point to an actual object.

As others have noted, you have to cast the void * to another type, most likely char * would be appropriate.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56