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;
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:
* (int *) element = set — heap;
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?