这个涉及指针的算术表达式发生了什么?

Ale*_*lex 4 c pointers

这是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 */
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白以下表达式中发生了什么:

allocbuf + ALLOCSIZE - allocp >= n
Run Code Online (Sandbox Code Playgroud)

我知道allocbuf作为数组名称相当于指向第一个元素和allocbuf [0]的指针,显然allocp是一个指针,最后ALLOCSIZE是一个简单的int.因此,将ALLOCSIZE添加到allocbuff会给出allocbuff的ALLOCSIZE索引元素,它也是一个指针.但是从指针和allocbuf [ALLOCSIZE]中减去指针allocp是我丢失的地方.我甚至不确定可以在C中添加指针.

请告诉我我错在哪里或我在这个解释中缺少什么.

这个程序的重点是存储字符.

Bar*_*rry 11

代码是一个固定缓冲区分配器,并检查以确保至少n剩下字节数.它有助于以图形方式查看内容,并且通过图形方式我的意思是与MSPaint:

分配器

所以打破表达:

allocbuf + ALLOCSIZE - allocp >= n
Run Code Online (Sandbox Code Playgroud)

allocbuf + ALLOCSIZE是数组的结尾.结束与allocp剩余字节之间的差异.所以我们只是检查以确保差异至少n.

减去两个指针,只要它们指向同一个数组中的元素(或者一个接一个的结尾),就可以很好地定义它们之间的元素数量.作为一个简单的例子,allocbufallocbuf + ALLOCSIZE是两个指针(型的char*),和(allocbuf + ALLOCSIZE) - allocbuf == ALLOCSIZE,元件的数量(类型的char它们之间的,在这种情况下).


zos*_*ska 7

从指针中减去指针将为您提供(如果它们是兼容的)元素数量(大小由指针指向的类型确定).

所以:

allocbuf + ALLOCSIZE
Run Code Online (Sandbox Code Playgroud)

指针指向allocbuf的最后一个元素

allocbuf + ALLOCSIZE - allocp
Run Code Online (Sandbox Code Playgroud)

allcobuf(+ 1)的最后一个元素和allocp之间留下的元素数量

在这种情况下:

allocbuf + ALLOCSIZE - allocp >= n
Run Code Online (Sandbox Code Playgroud)

确定是否留下足够的元素allocbuf以适合n元素.

编辑:

您可以将它与数组进行比较:如果您有指向第一个元素(将被索引0)的指针和第二个指针,它指向元素大小的4倍(这将指向5个索引为4的元素),那么当您是减去这两个,你会得到它们之间的4个元素(比如从索引4中减去索引0).但是只有当指针指向相同的内存缓冲区时(例如在数组中)才有意义.

所以这:

int array[5] = {1, 2, 3, 4, 5, 6};
int a* = &array[0] //equivalent to array
int b* = &array[4]
Run Code Online (Sandbox Code Playgroud)

还有这个:

int *array = malloc(6 * sizeof(int));
//set array values
int *a = array;
int *b = array + 5;
Run Code Online (Sandbox Code Playgroud)

(几乎)是一样的.