String Question: Why do we subtract a one to access the last character?

This is a discussion on String Question: Why do we subtract a one to access the last character? within the C++ Programming forums, part of the General Programming Boards category; I know in C the last character was the null character, but I'm confused what this means? Code: if ( ...

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    67

    String Question: Why do we subtract a one to access the last character?

    I know in C the last character was the null character, but I'm confused what this means?

    Code:
    if ( sz[ strlen( sz ) - 1 ] == '\\' )    // Is last character a '\'?
        // . . .
    so why do we subtract it by one?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Arrays start at zero. If strlen is 8, and you want to access the eighth letter, what number should you put in the brackets?

  3. #3
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,622
    Quote Originally Posted by newbc View Post
    I know in C the last character was the null character, but I'm confused what this means?

    Code:
    if ( sz[ strlen( sz ) - 1 ] == '\\' )    // Is last character a '\'?
        // . . .
    so why do we subtract it by one?
    If you didn't you would see the terminating zero instead.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,288
    Think about the smallest case possible.
    A string one character long, just an X say. It will have sz[0] = 'X' and sz[1] = '\0' (null terminator).
    Clearly the string length here is 1, but clearly you don't want to get sz[1].
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. shift-and-subtract divider
    By tox0tes in forum C Programming
    Replies: 1
    Last Post: 01-17-2010, 12:22 AM
  2. comparing character in a string to anothr character
    By merike in forum C Programming
    Replies: 5
    Last Post: 05-11-2007, 12:16 AM
  3. Question about string & character array
    By Roy01 in forum C++ Programming
    Replies: 6
    Last Post: 11-19-2006, 08:50 AM
  4. Question on character string
    By dv007 in forum C++ Programming
    Replies: 4
    Last Post: 02-06-2006, 11:17 AM
  5. Add, Subtract Calculator...
    By Crash1322 in forum C++ Programming
    Replies: 8
    Last Post: 12-14-2003, 10:38 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21