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

  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,336
    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
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    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,318
    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, 01: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, 09:50 AM
  4. Question on character string
    By dv007 in forum C++ Programming
    Replies: 4
    Last Post: 02-06-2006, 12:17 PM
  5. Add, Subtract Calculator...
    By Crash1322 in forum C++ Programming
    Replies: 8
    Last Post: 12-14-2003, 11:38 PM