Although it runs correctly, the following results in the aforementioned compiler warning:
return ((item - (my->items))/(my->itemSize));
'item' is a 'void *'; 'my->items' is a 'void *'; 'my->itemSize' is an 'int'
Casting 'item' and 'my->items' as an 'int *' caused the program to run improperly. What is the best way to remove the warning?
The void type has three important uses: To signify that a function returns no value. To indicate a generic pointer (one that can point to any type object) To specify a function prototype with no arguments.
A void pointer is a pointer to incomplete type, so if either or both operands are void pointers, your code is not valid C. Note that GCC has a non-standard extension which allows void pointer arithmetic, by treating void pointers as pointer-to-byte for such cases.
Since void is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation. Therefore you cannot perform pointer arithmetic on a void pointer.
Can math operations be performed on a void pointer? No. Pointer addition and subtraction are based on advancing the pointer by a number of elements.
Additions and subtractions with pointers work with the size of the pointed type:
int* foo = 0x1000;
foo++;
// foo is now 0x1004 because sizeof(int) is 4
Semantically speaking, the size of void
should be zero, since it doesn't represent anything. For this reason, pointer arithmetic on void
pointers should be illegal.
However, for several reasons, sizeof(void)
returns 1, and arithmetic works as if it was a char
pointer. Since it's semantically incorrect, you do, however, get a warning.
To suppress the warning, use char
pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With