Thread: character arrays

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    18

    Question character arrays

    i'm new to programming and would like to know whether the maximum no. of characters that an array of characters
    eg. char c[10]
    would be 10 or 11(adding the null character)
    thanks!!

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    [10] means 10 elements. If that array is used as a string then it is expected that the string terminates with a null. Therefore, the string has a maximum up to 9 non-null characters maximum, followed by null.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Code:
    char c[10];
    The maximum number of characters in this array would be 10. They are indexed from 0 to size-1. This means that the array consists of the following elements:

    Code:
    c[0]
    c[1]
    c[2]
    c[3]
    c[4]
    c[5]
    c[6]
    c[7]
    c[8]
    c[9]
    If you're making a string (an array of characters terminated with a null character, '\0'), then it's up to you, the programmer, to make sure the number of elements is large enough to fit the null character.

  4. #4
    Registered User
    Join Date
    Mar 2013
    Posts
    18
    got it...thanks!

  5. #5
    Registered User
    Join Date
    Mar 2013
    Posts
    18
    Code:
    char s[10];
    printf("%c", s[15]);
    if char s[10] represents a character array of 10 elements then why does printing s[15] give a garbage value instead of showing an error at accessing an element that does not exist??

  6. #6
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    One of the beauties of C. There is no run-time checking of array bounds. The programmer is free to make bugs such as this... the most common form of bug. Accessing an array beyond its defined bounds will get garbage - or you could cause a more severe effect if you are violating some memory privilege area.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Character Arrays - 1.9 in K&R. need help
    By NickDesigner in forum C Programming
    Replies: 15
    Last Post: 07-29-2011, 01:35 PM
  2. character arrays
    By enkwiringmindz in forum C Programming
    Replies: 8
    Last Post: 02-10-2010, 01:28 AM
  3. Character Arrays
    By danielakkerman in forum C Programming
    Replies: 5
    Last Post: 05-20-2007, 04:48 AM
  4. Character arrays
    By PsychoBrat in forum C++ Programming
    Replies: 7
    Last Post: 06-21-2002, 12:02 PM
  5. help with character arrays
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 03-28-2002, 06:13 PM