#define ALLOCSIZE 10000 /* size of available space */
staticchar allocbuf[ALLOCSIZE]; /* storage for alloc */
staticchar *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;
}
The logic here I don't understand:
if (allocbuf + ALLOCSIZE - allocp >= n)
allocbuf is a char array allocated with 10000 positions. We add that to ALLOCSIZE macro which is 10000. Does that return a value of 20000? If so, it doesn't make sense to do this because all we had to do was this:
if (allocbuf - allocp >= n)
That takes length of allocbuf which is 10000 and subtracts allocp from it. So if allocp is 1000 we are left with 9000 available slots. And we can use that to check if we have enough to allocate n elements.
no, its called pointer arithmetic. lets say i have this: int i[]={0,1,2,3,4,5,6,7,8,9};//an array with 10 elements
if i then do this: int x=*(i+7); x is set to the 7th element ie 7 (i think... im gonna be lazy and not count)
so this could have also been written as: int x=i[7];//like the processor ;)
so whats its doing is seeing if allocbuf[ALLOCSIZE] - allocp >= n
DTSCode you are right. The whole section was about pointer arithmetic. allocbuff returns the first index of the array. ALLOCSIZE is used for pointer arithmetic returning the value at the last position. So what this is basically saying is what you wrote before: if allocbuf[ALLOCSIZE] - allocp >= n
In case of char, as in the given example allocbuff + ALLOCSIZE can become 10000+10000 right? It's the same pointer arithmetic only one byte per character?