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

标签 c arrays pointer-arithmetic

我在一本书里有这个例子:

#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) 

最佳答案

引用 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) {

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

关于c - 数组变量的 "value"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283634/

相关文章:

c - 对一个过去的数组元素进行指针运算,然后取消引用,结果会是什么?

c - 这段代码如何在不使用 sizeof( ) 的情况下确定数组大小?

c - Strtok 在第一个标记后返回 (null)

c - 指针到指针的地址和算术

c - 利用缓冲区溢出读取操作

javascript - For循环if语句困惑

arrays - 将字典键和值重用到可重用单元格中

c++ - 函数采用预期大小的数组,向用户发出信号

c - 在配置脚本中处理 CFLAGS 的最佳实践?

c - 理解这个 C 数组语法 - 3[arr]