tags:

views:

101

answers:

4

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?

+8  A: 

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

sizeof(void) is zero. Therefore, it's semantically wrong to increment or decrement void pointers, because it should not change its value. However, your compiler is likely smart enough to figure out that you want to perform the operations as if your pointers were actually integers, so it makes it work for you.

Cast your pointers to char pointers (since sizeof(char) is 1) and you should be fine.

zneak
+1 Good Answer !!!!!!
Romain Hippeau
A: 

The problem is that you are doing aritmethical operations in a pointer, I wonder how is that running properly.

Francisco Soto
What's wrong with performing pointer arithmetic?
dreamlax
There's nothing wrong with pointer arithmetic, I misread the code and thought he was doing normal math, not pointer. My bad :)
Francisco Soto
A: 

If you're trying to do normal arithmetic, you have to dereference the pointer (e.g. *item). If you're trying to do pointer arithmetic, the pointer has to be of a type, like char* or int* (otherwise the compiler won't know how much to increment by).

eman
+1  A: 

Cast to a char *:

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

Since char is size of 1 byte, you will get the value you are expecting vs your int * pointer example which calculates how many ints are between the two address. That's how pointer arithmetic works.

Jim Buck