Thread: '/0' in strings

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    83

    '/0' in strings

    Hi,

    I wrote the following code:

    Code:
    #include <stdio.h>
    
    
    int main(void)
    {
        char str[100] = "Hello world";
        char *last;
        
        for(last = str; (*last) != '\0'; last++)
            ;
        
        last--;
        printf("last char: %c\n", *last);
        
        return 0;
    }
    Now I'm wondering why I need the statement last--; to get the last char. Shouldn't the for loop stop before reaching '\0'?
    I was thinking the same program as above but leaving out the last--; would give us output: 'd'.

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    And what output does it produce without the last--?

    Shouldn't the for loop stop before reaching '\0'?
    No, it stops when it reaches the termination character.

    Jim

  3. #3
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    Hi,
    in C strings are 0-terminated, your statement
    char str[100] = "Hello world";
    automatically appends a (char) 0 ; so the last character of a string is followed by (char) 0.
    Your for-loop moves pointer "last" forward until the address where it points to has a value of (char) 0, this is 1 byte further than the last character of your string.
    last-- puts your char-pointer 1 byte back so that it points to the last character (one byte before the '\0'.

  4. #4
    Registered User
    Join Date
    Sep 2014
    Posts
    83
    Ah ok, got it now, thanks!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-16-2012, 06:08 AM
  2. Swapping strings in an array of strings
    By dannyzimbabwe in forum C Programming
    Replies: 3
    Last Post: 03-03-2009, 12:28 PM
  3. malloc() strings VS array strings
    By Kleid-0 in forum C Programming
    Replies: 5
    Last Post: 01-10-2005, 10:26 PM
  4. Table mapping Strings to Strings
    By johnmcg in forum C Programming
    Replies: 4
    Last Post: 09-05-2003, 11:04 AM
  5. converting c style strings to c++ strings
    By fbplayr78 in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 03:13 AM