Thread: newbie: array question :(

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    61

    Cool newbie: array question :(

    sup guys its me the newbie c student again! hope u guys didnt get tired by my whole lots of newbie questions well.. i have another doubt to be cleared.. here's it:

    lets say we have 2 strings:
    Code:
    char a[] = {'h','e','l','l','o','\0'};
    char b[10] = "hello"
    is b[5] == a[5]?

    from what i know, b[5] is = \0, therefore, i deduced that b[5] == a[5] is true. what if i compare b[6] == a[5] ?? am i correct?

    Thanks for all the answers, im learning alot of stuff here

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    is b[5] == a[5]?
    Yes, but you could have checked that yourself with a test program.

    what if i compare b[6] == a[5] ??
    b[6] should also be '\0'.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    b[6] should also contain zero, so yes, b[6] and a[5] are identical in this case.

    Of course, if you do:
    Code:
    char a[] = {'h','e','l','l','o','\0'};
    char b[10];
    
    strcpy(b, a);
    then b[6] is undefined - it may happen to be zero, but it's just as likely to be some other value between -128 and 127 (or 0..255 if char happens to be unsigned in your compiler).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie question about 'sizeof' and arrays
    By Sharke in forum C Programming
    Replies: 27
    Last Post: 12-09-2009, 06:30 AM
  2. Embaracing Array question
    By DavidDobson in forum C Programming
    Replies: 2
    Last Post: 04-06-2009, 10:29 AM
  3. Quick Question: 2D Array with char **
    By Phoenix_Rebirth in forum C Programming
    Replies: 4
    Last Post: 01-29-2009, 07:33 AM
  4. newbie array question
    By chris1985 in forum C Programming
    Replies: 3
    Last Post: 05-05-2005, 03:43 AM
  5. Replies: 5
    Last Post: 05-30-2003, 12:46 AM