R
randomtalk
hello everyone!
Well, recently i've been trying to pick up c and see what is pointer
all about (been programming in lisp/python for the better part of my
last two years)..
mmm.. I'm currently reading The C Programming Language Second Edition..
When i hit on pointer arithmetic example, i have no idea what's
happening, hopefully some of you could alleviate my confusion, so here
goes:
Here is a few lines to illustrate my confusion:
#include <stdio.h>
int main(void)
{
char allocbuf[10000];
char *allocp = &allocbuf[3000];
printf("allocbuf is: %p, \n", allocbuf);
printf("allocp is: %p, \n", allocp);
printf("after addition, result is: %i \n", allocbuf+10000);
printf("after substracttion, result is: %i \n",
allocbuf+10000-allocp);
return 0;
}
Basically, in the book, they are trying to implment a trivial version
of malloc and free. First of all, allocate a size of the buffer, called
allocbuf, then *allocp points to next empty spot (here i just used 3000
for arguments sake), then for some reason, allocbuf + 10000 - allocp is
suppose to give you how much space is left (and it does, returns
7000).. However, conceptually (most likely it's mostly wrong), when an
10000 block array add 10000, and minus the used space, isn't suppose to
give you the free space.. That's where i got confused, also, neither
the printed result by either allocbuf, or allocbuf+10000 helped me..
So if any kind soul would help me, it would be greatly appreciated
Thanks!
Well, recently i've been trying to pick up c and see what is pointer
all about (been programming in lisp/python for the better part of my
last two years)..
mmm.. I'm currently reading The C Programming Language Second Edition..
When i hit on pointer arithmetic example, i have no idea what's
happening, hopefully some of you could alleviate my confusion, so here
goes:
Here is a few lines to illustrate my confusion:
#include <stdio.h>
int main(void)
{
char allocbuf[10000];
char *allocp = &allocbuf[3000];
printf("allocbuf is: %p, \n", allocbuf);
printf("allocp is: %p, \n", allocp);
printf("after addition, result is: %i \n", allocbuf+10000);
printf("after substracttion, result is: %i \n",
allocbuf+10000-allocp);
return 0;
}
Basically, in the book, they are trying to implment a trivial version
of malloc and free. First of all, allocate a size of the buffer, called
allocbuf, then *allocp points to next empty spot (here i just used 3000
for arguments sake), then for some reason, allocbuf + 10000 - allocp is
suppose to give you how much space is left (and it does, returns
7000).. However, conceptually (most likely it's mostly wrong), when an
10000 block array add 10000, and minus the used space, isn't suppose to
give you the free space.. That's where i got confused, also, neither
the printed result by either allocbuf, or allocbuf+10000 helped me..
So if any kind soul would help me, it would be greatly appreciated
Thanks!