Reputation: 23
#define ALLOCSIZE 10000 /* size of available space */
static char allocbuff[ALLOCSIZE]; /* STORAGE FOR alloc */
static char *allocp = allocbuff; /* next free position */
char *alloc(int n) /* return pointer to n characters */
{
if(allocbuff + ALLOCSIZE -allocp >=n) /*it fits */
{
allocp += n;
return allocp - n; /* old p */
}
else /*not enough room */
return 0;
}
in the above code allocp is pointer which is assigned with allocbuff which is the starting element address of allocbuff but why in comments it has been given that (char * allcop=allocbuff )will point to the next free element how is it possible it has to point to the first element naa
if allocp and allocbuff were both the stating element address why cant we directly give ALLOCSIZE>=N in if condition
code is as per dennis ritchie c book and topic is from address arithmetic
Upvotes: 0
Views: 668
Reputation: 34418
why in comments it has been given that (char * allcop=allocbuff )will point to the next free element how is it possible it has to point to the first element naa
It starts off pointing to the first element, but the function modifies it:
allocp += n;
i.e. once you've allocated n
characters we advance the allocp
pointer by n
so that it now points to the next free character after all of the characters that we've allocated so far.
if allocp and allocbuff were both the stating element address why cant we directly give ALLOCSIZE>=N in if condition
Because we change allocp, as above. We want to see if n
is greater than the size we've got left in our buffer, so we need to compute that. allocbuff + ALLOCSIZE
is the end of the buffer (not inclusive) so allocbuff + ALLOCSIZE - allocp
is the number of characters remaining.
Upvotes: 2