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

Although it works correctly, the following warnings are in the above compiler warning:

return ((item - (my->items))/(my->itemSize)); 

'item' is 'void *'; 'my-> items' is 'void *'; 'my-> itemSize' is 'int'

Casting 'item' and 'my-> items' as 'int *' made the program work improperly. What is the best way to remove a warning?

+4
source share
4 answers

Additions and subtractions with pointers work with a pointed type size:

 int* foo = 0x1000; foo++; // foo is now 0x1004 because sizeof(int) is 4 

Semantically, the void size must be zero, because it does not represent anything. For this reason, pointer arithmetic on void pointers must be illegal.

However, for several reasons, sizeof(void) returns 1, and arithmetic works as if it were a char pointer. However, since this is semantically incorrect, you nevertheless receive a warning.

To suppress the warning, use char pointers.

+16
source

Passing to char * :

 return ((char *)item - (char *)my->items)/my->itemSize); 

Since char is 1 byte in size, you get the expected value compared to your example int * pointer, which calculates how much int is between two addresses. The way pointer arithmetic works.

+3
source

The problem is that you are performing aritmethical operations in a pointer, I wonder how this works properly.

0
source

If you are trying to do regular arithmetic, you must dereference a pointer (e.g. *item ). If you are trying to perform pointer arithmetic, the pointer must be of type, for example, char* or int* (otherwise the compiler will not know how much to increase).

0
source

Source: https://habr.com/ru/post/1307977/


All Articles