I want to create a function which gets a void pointer. This pointer points to an arbitrary user data. This is not relevant now. Which is more important a descriptor, which describe this user data. It is under this data. I want to get it’s address, there are two different solution:
struct data_desc {
size_t size;
data_type_t type;
/* And so on... */
};
/* Operate on the descriptor */
void operate_on_data(void *ptr)
{
struct data_desc *desc;
/* Now I want to get the desc /*
/* This is the first approach, simply fails */
desc = ((struct data_desc *)ptr) - sizeof(struct data_desc);
/* This is the second, it works...*/
desc = (struct data_desc *)ptr;
desc--;
/* Do something with desc */
}
As you can see I use two diffrent approach to get the descriptor’s address. I thought the first is more natural, but it’s just not works. I used more parentheses to avoid the precedence problems.
I know that these methods are not safe. The first does not work, why? What is the reason behind this behavior?
Thanks in advance!
The problem is pointer arithmetic. When you take a pointer and subtract 1, you are really subtracting
(1*sizeof(struct)). The first equation with the “-sizeof”, you are really subtracting(sizeof(struct) * sizeof(struct))bytes from the pointer. Make sense?