Thread: C strings help

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    13

    C strings help

    Hi all, on the C programming tutorial on this website is 'Lesson 9 - C strings:
    C Strings - C++ Tutorial - Cprogramming.com

    Given in this lesson is the following:

    Code:
    #include <stdio.h>    /* stdin, printf, and fgets */
    #include <string.h>   /* for all the new-fangled string functions */
    
    /* this function is designed to remove the newline from the end of a string
    entered using fgets.  Note that since we make this into its own function, we
    could easily choose a better technique for removing the newline.  Aren't
    functions great? */
    void strip_newline( char *str, int size )
    {
        int i;
    
        /* remove the null terminator */
        for (  i = 0; i < size; ++i )
        {
            if ( str[i] == '\n' )
            {
                str[i] = '\0';
    
                /* we're done, so just exit the function by returning */
                return;   
            }
        }
        /* if we get all the way to here, there must not have been a newline! */
    }
    
    int main()
    {
        char name[50];
        char lastname[50];
        char fullname[100]; /* Big enough to hold both name and lastname */
    
        printf( "Please enter your first name: " );
        fgets( name, 50, stdin );
    
        /* see definition above */
        strip_newline( name, 50 );
    
        /* strcmp returns zero when the two strings are equal */
        if ( strcmp ( name, "Alex" ) == 0 ) 
        {
            printf( "That's my name too.\n" );
        }
        else                                     
        {
            printf( "That's not my name.\n" );
        }
        // Find the length of your name
        printf( "Your name is %d letters long.\n", strlen ( name ) );
        printf( "Please enter your last name: " );
        fgets( lastname, 50, stdin );
        strip_newline( lastname, 50 );
        fullname[0] = '\0';            
        /* strcat will look for the \0 and add the second string starting at
           that location */
        strcat( fullname, name );     /* Copy name into full name */
        strcat( fullname, " " );      /* Separate the names by a space */
        strcat( fullname, lastname ); /* Copy lastname onto the end of fullname */
        printf( "Your full name is %s\n",fullname );
    	printf("It's a pleasure to be talking with you %s\n", name);
        getchar();
    
        return 0;
    }
    I am confused as to why:
    Code:
    fullname[0] = '\0';
    is included.
    In the tutorial is states that C style strings are always terminated with a null character ('\0'). I don't understand why the beginning of the string 'fullname' would be set to this. In the code it states:
    Code:
    fullname[0] = '\0';            
    /* strcat will look for the \0 and add the second string starting at
       that location */
    Is the string 'lastname' the second string? If so why is it seemingly being put at the start of the 'fullname' string. Even though, through running this code i know this isn't what is happening.
    Without 'fullname[0] = '\0';', the program crashes and I have no idea as to why this happens.

    Thankyou for any help.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Because of the use of strcat(). Optionally (and in fact more conventionally -- I would guess the tutorial is purposefully written this way to indicate something about the functionality of strcat) that section could have been:

    Code:
        strip_newline( lastname, 50 );
      /* use strcpy instead of strcat*/
        strcpy( fullname, name );     /* Copy name into full name */
    in which case fullname[0] = '\0' is not necessary.

    Hopefully you can connect the dots there, if not ask for further clarification!
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    The first character in fullname is set to '\0', the NULL character, to make C think it is an empty string. strcat() appends the second parameter to the end of the first parameter; it basically finds the end of the string given by the first parameter by searching for a '\0', and then copies characters over from the second parameter until it reaches a '\0' there.

    If fullname is uninitialized, as it is until fullname[0] is set to '\0', there's no telling what might be in it. strcat() will try to search for the end of the string, denoted by a '\0'; it might have to go quite a way through memory until it finds a '\0' by chance, and at this point it's probably outside the memory allocated for your program and trying to overwrite some other program's memory. The operating system detects this and kills your program.

    By the way, in real code it would probably be simpler to just change the first strcat() call to a strcpy() call. This copies the second parameter into the string given by the first parameter, starting at index 0, without trying to preserve any data that might have been there before; you can safely strcpy() into an uninitialized array.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    13
    Brilliant, thankyou!

    So a code that does the same thing using strcpy:
    Code:
    strcpy(fullname, name);
    strcat(fullname, " ");
    strcat(fullname, lastname);
    Thanks again!

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Another way to accomplish that:

    Code:
    sprintf(fullname, "%s %s", name, lastname);
    better would be to use snprintf, so you have a guarantee not to overrun your buffer:

    Code:
    snprintf(fullname, sizeof(fullname), "%s %s", name, lastname);
    Last edited by rags_to_riches; 05-30-2010 at 01:52 PM. Reason: Added snprintf

  6. #6
    Registered User
    Join Date
    Apr 2010
    Posts
    4
    You guys are so clever.I think I have understood something better.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  2. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  3. Problems with strings as key in STL maps
    By all_names_taken in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 11:34 AM
  4. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM
  5. menus and strings
    By garycastillo in forum C Programming
    Replies: 3
    Last Post: 04-29-2002, 11:23 AM

Tags for this Thread