Reputation: 1
Im trying to store the size of an array of an arbitrary type in front of the array so that the size can be accessed through the -1st element of the array. The goal of my function is to increment the array back by the size of an int pointer (where the size should be stored) and return that to the calling function.
The issue i'm having is that when the array is of type int, the incrementation isnt happening correctly and is returning the wrong value. However, when the array is of type double, it works perfectly. Here is the code for the function:
int getSizeArray(void * array)
{
return *((int*)(array - 1));
}
Upvotes: 0
Views: 547
Reputation: 19375
We can't sensibly perform arithmetic with a void
pointer (array - 1
); rather cast array
to the actual type first:
return ((int *)array)[-1];
Of course it is assumed that array
as well as this size element is initialized correctly.
Upvotes: 2