什么是数组变量的"value"?

What is the "value" of an array variable?

我在书中有这个例子:

#define ALLOCSIZE 10000 /* 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 */
        allocp += n;
        return allocp - n; /* old p */
    } else /* not enough room */
      return 0;
}

void afree(char *p) /* free storage pointed to by p */
{
     if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
         allocp = p;
}

我需要知道 allocbuf 代表什么(它的值)所以它用于:

if (allocbuf + ALLOCSIZE - allocp >= n) 

在这种情况下,数组衰减为指向其存储位置的指针。换句话说:指向其第一个元素的指针。

您可以使用 allocbuf(或者更好:&allocbuf[0],它更好地传递了 "pointer to the first element" 的含义)来获取指向第一个元素的指针,并且 allocp旨在指向下一个空闲元素。所以 allocp - allocbuf 会给你元素的数量 "used".

引用 C11,章节 §6.3.2.1/p3,(强调我的

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]

所以,在你的代码中,allocbuf,这是一个数组类型,当用作

if (allocbuf + ALLOCSIZE - allocp >= n) {

将衰减到指向数组第一个元素的指针。