Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: pointer of type 'void *' used in subtraction

Tags:

c

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?

like image 918
idealistikz Avatar asked Apr 26 '10 03:04

idealistikz


People also ask

Why is the type void * Used?

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.

What does the void pointer can be difference?

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.

Why is pointer arithmetic not applicable on void?

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?

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.


1 Answers

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.

like image 176
zneak Avatar answered Sep 21 '22 06:09

zneak