I am rather new to C and I am having a hard time getting a hang of all these pointers. In other words the dereferencing operator and the ampersand operator. I believe, after staring at them for a while I am starting to understand how they work. For example:
int x = 1; //this creates an integer variable called x and assigns one to it
int *pointer; //this creates a pointer variable that will point to an integer
pointer = &x; //now the variable pointer points to x
*pointer = 0 //the value that pointer points to is now zero
I'm pretty sure I understand how that works.
I am reading through "The C Programming Language" by Kernighan and Ritchie but I am confused by their some code they have in section 5.4 (address arithmetic). I should point out that I understand address arithmetic so my question does not pertain to that. Nor is my question about the code inside the below function does. Searching online for questions about this code generates a lot of posts where people do not understand how the code in the if/else statement operates. In any case, my question is specifically about the function name itself.
#define ALLOCSIZE 1000
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;
char *alloc(int n) /*return pointer to n charachters*/
{
if (allocbuf + ALLOCSIZE - allocp >=n)
{
allocp += n;
return allocp - n;
}
else
return 0;
}
Again, I understand the code in the function but how does
*alloc
work? I understand this function returns a pointer. Does this imply that by having the function name be a pointer we are returning a pointer to a char type? If so, what does it point to? In my earlier example, we have
int x = 1;
int *pointer;
pointer = &x;
Here the variable "pointer" is pointing to the x variable. However. in the function alloc doesn't point to anything. Any help would be appreciated.