Thread: The last character of a string

  1. #1
    Registered User
    Join Date
    Nov 2020
    Posts
    14

    The last character of a string

    Code:
    int main()
    {
      int lastDigit;
      char num1[3] = "123";
      lastDigit = strlen(num1) - 1;
      printf("%c", num1[lastDigit]);
      return 0;
    }
    Guys, any idea why this code doesnt work?
    I want to get the last character of the string. In that case its "3"
    Last edited by Salem; 11-06-2020 at 03:03 AM. Reason: Removed eye-bleed colour scheme

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Because
    char num1[3] = "123";
    does NOT have a \0 at the end of it for strlen() to do it's thing properly.

    Write
    char num1[4] = "123";
    or better, let the compiler do the work
    char num1[] = "123";
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read string length when string contains the null character
    By DecoratorFawn82 in forum C Programming
    Replies: 4
    Last Post: 01-06-2018, 09:07 AM
  2. How to read character by character without string.h?
    By Jimmy King in forum C Programming
    Replies: 2
    Last Post: 10-29-2013, 01:00 AM
  3. comparing character in a string to anothr character
    By merike in forum C Programming
    Replies: 5
    Last Post: 05-11-2007, 12:16 AM
  4. Replies: 3
    Last Post: 11-03-2002, 02:14 AM

Tags for this Thread