Page 118 - Programming Microcontrollers in C
P. 118
Structures 103
return (TNODE *) malloc(sizeof(TNODE);
will return to the calling function a pointer of the type TNODE to a
free memory space the size of a TNODE. This function is called by
the function addtree(). You will note that addtree() does
not test the return from talloc() to determine if the return is a
NULL pointer. Good programming practice would dictate that the
return from talloc() should be tested to make certain that
malloc() did not return a NULL pointer.
The next function that must be incorporated into the program is
getword(). getword() returns the first character of the word
or an EOF in the case that an EOF is detected. It requires two argu
ments. The first is a pointer to a character array into which the input
data are to be stored. The second argument is the length of the array
and hence the maximum length of any word that can be read into the
program by getword(). Two functions are accessed by
getword(). The first is getch() which returns a character from
the input stream. The second is ungetch() which restores a char
acter back onto the input stream. We will see later that for getword()
to work correctly, it must pull one more character than the length of
the word in some cases. When that happens, the extra character must
be put back onto the input stream so that it will be available for the
next getch() call.
/* getword: get next word or character from input */
int c, getch(void);
void ungetch(int);
int getword(char *word, int lim)
{
char *w=word;
while(isspace(c=tolower(getch())));
if(c!=EOF)
*w++=c;
if(!isalpha(c))
{
*w=‘\0’;
return c;
}
for( ; —lim >0 ; w++)