【发布时间】:2015-08-24 13:17:28
【问题描述】:
这是 C 中的代码:
#define ALLOCSIZE 1000 /* size of available space */
static char allocbuf[ALLOCSIZE]; /* storage for alloc */
static char *allocp = allocbuf; /* next free position */
char *alloc(int n) /* return pointer to n characters */
{
if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */
...
}
}
我不明白以下表达式中发生了什么:
allocbuf + ALLOCSIZE - allocp >= n
我知道allocbuf作为一个数组名相当于一个指向第一个元素&allocbuf[0]的指针,而显然allocp是一个指针,最后说ALLOCSIZE是一个简单的int。因此,将 ALLOCSIZE 添加到 allocbuff 会得到 allocbuff 的 ALLOCSIZE 索引元素,它也是一个指针。但是从指针 &allocbuf[ALLOCSIZE] 中减去指针 allocp 是我迷路的地方。我什至不确定是否可以在 C 中添加指针。
请告诉我我在哪里错了或者我在这个解释中遗漏了什么。
这个程序的重点是存储字符。
【问题讨论】:
-
您不能添加指针,但可以减去它们以获得距离(以对象数为单位)。想想
allocbuf + ALLOCSIZE - allocbuf。结果如预期 -ALLOCSIZE. -
两个指针
b - a之差是a和b之间的元素个数。所以,allocbuf - allocp是-1乘以已分配的元素数。 -
那
if与if (ALLOCSIZE >= n)相同。无法添加指针,因为它没有意义。但是,它可以被减去。 (谷歌“减去指针 c”以获取更多信息) -
@CoolGuy 鉴于
allocp永远不会改变,是的,但这可能是一个糟糕的假设。