Whatdoes*(int*)variable=valuemean?
I am reading the online book Object-Oriented Programming with ANSCI-C
Page 6 shows an implementation of a set. There is an add() function that takes two parameters: a set and an element. The element is added to the set. The implementation uses an array of pointers:
static int heap [MANY];
Here is the beginning of the add() function:
void * add (void * _set, const void * _element)
{
int * set = _set;
const int * element = _element;
if (* element == MANY)
* (int *) element = set — heap;
It is that last line:
* (int *) element = set — heap;
* (int *) element = set — heap;
that I do not understand. It appears that the right-hand side is subtracting pointers, is that right? Is that common to subtract pointers? On the left-hand side it appears that (int *) is casting element to a "pointer to an int", is that right? The star at the beginning appears to indicate "the value of the thing being pointed at", is that right?
Sorry, I am lost. What is the code saying?
Update (a question based on the responses)
Thank you for the outstanding responses!
I have a follow-up question about this expression: set - heap
heap is the name of an array. set is one of the cells in heap, say, heap[2]. So, the expression is subtracting the pointer to heap from the pointer to heap[2], is that right? I used a printf() statement to output heap and output set, here's what it output:
heap = 4227136
set = 4227140
So, set - heap equals 4. Does that mean set is pointing at heap[4] (i.e., 4 cells from the start of the array)? Is the pointer to heap[i+1] always guaranteed to be 1 more than the pointer to heap[i]?
I output the value of element after this statement was executed:
As just discussed, the value of set - heap is 4. The output says the value of element is 1. How can that be, shouldn't the value of element be 4?
回答
Since *element is a const int, it can't directly be assigned.
So the cast
* (int *) element = set — heap;
converts element to int * and then dereferences, then assigns the result of set - heap.
However, this is only valid if:
- the original object that
_elementpoints to is a modifiable object. Otherwise, casting away theconstis undefined behaviour. - that points to an
intobject.
Yes, set - heap is subtracting two pointers. But it could be invalid because:
-
the result of subtracting two pointer yields a
ptrdiff_twhich may or may not fit in aninttype. -
减法仅在两个指针指向同一个数组对象或指向数组对象的最后一个元素之后才有效。见6.5.6 加法运算符/9
总而言之,该代码可以解决您的问题。但需要满足上述条件才有效。