[Courses] [C] Lesson12: Exercise answers

Laurel Fan laurel at sdf.lonestar.org
Wed Nov 20 13:33:23 EST 2002


Comments inline:

On Wed, Nov 20, 2002 at 09:51:03PM -0500, Morgon Kanter wrote:
> [2] Write a function that takes a single string as its argument and
>     returns a pointer to the first nonwhite character in the string.
> /* Begin */
> #include <stdio.h>
> 
> char *stringlook(char *string);
> 
> int main() {
>    char string[80];
>    char *stringpointer;
>    unsigned short int i;
> 
>    printf("Enter a string: ");
>    fgets(string, sizeof(string), stdin);
> 
>    /* trim off the newline character here */
>    for(i=0; string[i] != '\0'; i++) {
>       if(string[i] == '\n') {
>          string[i] = '\0';
>          break;
>       }
>    }
> 
>    printf("String reads: %s\n", string);
>    stringpointer = stringlook(string);
>    printf("Pointer reads: %c\n", *stringpointer);

If you're not sure about whether a pointer is valid, it is a good idea
to make sure it is before dereferencing (using the * operator) it.  I
would do something like this:

    stringpointer = stringlook(string);
    if (stringpointer == NULL) {
        printf("Did not find any non-whitespace characters.\n");
    } else {
        printf("Pointer reads: %c\n", *stringpointer);
    }

I do this because dereferencing an invalid pointer can crash a
program, or, worse, screw things up in a less easily detectable way.
This sort of bug is very common.  If you've ever seen "Segmentation
Fault" on unix or "General Protection Fault" on windows, it's probably
because something dereferenced an invalid pointer.

What happens if you give your program a string with all spaces?  Also
see my note about stringlook below.

> 
>    return 0;
> }
> 
> /* Searches the string for the first non-white character and
>  * returns a pointer to it. If there is none, it returns 1. */

When a function returns a pointer, the usual way to indicate an error
condition is to return NULL.  NULL means an invalid pointer (NULL == 0
everywhere I've seen it).  For example, the strchr function, which
searches for a character in a string, returns NULL if the character
does not exist (man strchr for more details).

> char *stringlook(char *string) {
>    unsigned short i;
> 
>    for(i=0; *(string+i) != '\0'; i++) {
>       if( *(string+i) != ' ') return (string+i);
>    }
> 
>    return 1;

I would do:
     return NULL;
here instead.
> }

-- 
laurel at sdf.lonestar.org
http://dreadnought.gorgorg.org



More information about the Courses mailing list