C Problem with array / pointer

Going through K & R I will also consider 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 am afraid that my question is very simple, but I can’t get around the if line. What is the value of allocbuf? This is a char array, right? I looked back at the array material in the book, but that didn't help. allocp initially points to the null element of the array, right?

+5
source share
4 answers

allocbufis an array of type char [], but in many contexts, the identifier itself decays into a type pointer char *containing the starting address of the array. Note that this does not mean that it allocbufis a pointer, it is still an array.

, if .

+2

-, allocp allocbuf char (char *), allocp char if "body", + , "if". , char . "if", , ​​ , n allocbuf, . :

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

"ALLOCSIZE", : , ? , - , MAXLINE, , .

+1

allocbuf , 0. allocbuf + ALLOCSIZE . allocp , - . allocbuf + ALLOCSIZE-allocp . if , (n) , .

0

allocbuf - , (). allocp - , , .

0

All Articles