C Array/Pointer problem
Going thr开发者_C百科ough K&R I too a look at the following code:
#define ALLOCSIZE 1000
static char allocbuf[MAXLINE];
static char *allocp = allocbuf
char *alloc(int n){
if (allocbuf+ALLOCSIZE-allocp>=n){
allocp+=n;
return allocp-n;
}
else { ... }
I'm afraid my question is very simple, but I can't get my head round the "if" line. What value is allocbuf taking? It is a char array, right? I looked back at the array stuff in the book, but it didn't help. allocp initially points to the zeroth element of the array, right?
allocbuf
is an array of type char []
, but in many contexts the identifier itself decays to a pointer of type char *
, holding the starting address of the array. Note that this doesn't mean that allocbuf
is a pointer, it is still an array.
So, the condition of the if
statement performs some pointer arithmetic.
While they're declared in different ways, allocp and allocbuf are both char arrays (char*) and allocp effectively points on the first char of the buffer after initializing, and after getting through the "if" body, to the same adress + the number of bytes allocated, and this number increases with each new cycle in the "if" body. To sum up, it points on the first free char in the buffer. The "if" line you're stuck with is aimed to verify if there's enough place for allocating n chars in the allocbuf, the static buffer. This line could be discomposed as follows :
char* static_buffer_beginning = allocbuf;
char* static_buffer_ending = static_buffer_beginning + MAXLINE;
int nb_chars_still_available = static_buffer_ending - allocp;
if (nb_chars_still_available >= n) {
I'm just a little confused by the "ALLOCSIZE" which appears in your code : what's his value, where does it come from?! I assume it's a typo or something like that and that its value is equal to MAXLINE, but would like to be sure for not to give you a wrong answer.
Think of allocbuf as the pointer to the beginning of your RAM, say 0. Then allocbuf+ALLOCSIZE will be pointing to the end of your RAM. allocp is pointing to the end of the allocated region, somewhere in the middle of your RAM. So allocbuf+ALLOCSIZE-allocp will give you the free memory size. The if statement checks if your requested allocation size (n) is less than the free memory available.
allocbuf is a static array, actually it points to first element of contiguous set of chars (the array). allocp is another pointer to the contiguous array and you can change its value to point to the array elements.
精彩评论