Why does Kernighan pg 106 work?
physics at utcsstat.UUCP
physics at utcsstat.UUCP
Wed Aug 10 04:54:34 AEST 1983
Here is a fragment of code based directly on p.106,107
of Kernighan & Ritchie:
#define SIZE 30000
#define BLOCKS 15000
main() {
char *blkptr[LINES]; /* Pointer to blocks of text, see f1 */
if((n = f1(blkptr)) >= 0){
m =f2(blkptr,n); writestrings(blkptr,m);
}
}
f1(blkptr)
char *blkptr[];
{
char s[SIZE]; /* Here is where the text is */
blkptr[0] = s;
while((s[i++] = getchar()) != EOF && i < (SIZE-1)))
;
s[i++] = '\0'; return(i);
}
f2(blkptr,n)
char *blkptr[];
{ for(i=0, i<n; i++){
if(something){
*(blkptr[0} + i) = '\0';
blkptr[++nblock] = blkptr[0] + (i + 1);
} } return(nblock);
}
This all works fine, except it is limited to an input size
of 30,000 chars, it eats a lot of memory, and the
application doesnt' require that
the whole thing be accessed at once. Obvious solution: set
SIZE to a round number like 512, add appropriate flags to
f1, and change the if in main() to a while. Except, when
one does that, on exit from f1 the array s gets garbage in
it. Changing the declaration of s to static char s[SIZE];
fixes the problem. But the question is ---- What's the difference
between an i_f and a w_h_i_l_e in main? For an i_f s does not get
clobbered, but for a w_h_i_l_e it does. Why does the code in
K & R, p106/107 work?
David Harrison
Dept. of Physics
Univ. of Toronto
...!linus!utzoo!utcsstat!physics
More information about the Comp.lang.c
mailing list