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];
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
It is that last line:
* (int *) element = set — heap;
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
converts element
to int *
and then dereferences, then assigns the result of set - heap
.
However, this is only valid if:
_element
points to is a modifiable object. Otherwise, casting away the const
is undefined behaviour.int
object.Yes, set - heap
is subtracting two pointers. But it could be invalid because:
the result of subtracting two pointer yields a ptrdiff_t
which may or may not fit in an int
type.
减法仅在两个指针指向同一个数组对象或指向数组对象的最后一个元素之后才有效。见6.5.6 加法运算符/9
总而言之,该代码可以解决您的问题。但需要满足上述条件才有效。
归档时间: |
|
查看次数: |
120 次 |
最近记录: |