Thread: beginner array question

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    288

    beginner array question

    well, when i started c/c++ programming, the book i read told me that to create an array, you need to put the number of 'elements' in the [...].

    for example, lets say i want to make a char-array capable of holding up to 4 letters, i would do:

    Code:
    char sWord[4];
    then i try putting data inside the char-array, for example:

    Code:
    sWord[0] = 'T';
    sWord[1] = 'E';
    sWord[2] = 'S';
    sWord[3] = 'T';
    sWord[4] = '/0';
    when i compile and run that program, it works fine most of the time, but if i have another char-array, i get some weird results.. when i set a value to sWord[3] or sWord[4], i get a value on sWord2[0]...

    im just wondering, if i wanted an array that could hold 4 letters (no need for a null char at the end), do i need to declare it as

    Code:
    char sWord[4];
    
    or
    
    char sWord[5];
    i was told that you can only use n - 1 elements, so for the first sWord, i would have 0 to 3, and for the second sWord, i would have 0 to 4...

    what happens if i try to write to sWord[4]?

    im not sure but, if i declare sWord[4], can i set sWord[4] to null? or is that not allowed.. somebody please explain this, ive been doing it this way for so long, and problems are only just starting to appear, and i want to know if im doing it right

    thanks

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> char sWord[4];

    well, that's four valid elements, right?

    >> sWord[4] = '/0';

    accessing the fifth element exceeds the valid bounds of the array.

    >> but if i have another char-array, i get some weird results.. when i set a value to sWord[3] or sWord[4], i get a value on sWord2[0]...

    because you accessed an invalid element in the first array, you actually corrupted the point of the stack where the one of the elements of the second array resides.

    just allocate an extra element for your char arrays for the null terminator and you won't have a problem, right?
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    288
    but i dont get 1 thing.. your declaring it as sword[4].. which is 4 elements (0-3) i get that, but.. what is the 5th element (sword[4]) used for?

    so if i want to declare a string, i need to include the null terminator in the no. of elements? and is it compulsory? or can i have strings that dont include a null terminator, if im going to treat them as char arrays rather then strings?

    btw, thanks for the reply, cleared a few things up, all this time ive been doing it all wrong :S

  4. #4
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Quote Originally Posted by X PaYnE X
    but i dont get 1 thing.. your declaring it as sword[4].. which is 4 elements (0-3) i get that, but.. what is the 5th element (sword[4]) used for?
    There is no sword[4].
    When you go like this:
    Code:
    char sword[4];
    You're actually creating 4 slots (including 0):
    Code:
    sword[0] = '1';
    sword[1] = '2';
    sword[2] = '3';
    sword[3] = '4';
    The only reason we always put '\0' is so that when we use the char array as a string, like:
    Code:
    puts(sword);
    The function puts(char *output) will know when to stop, because it stops printing out sword when it hits the '\0' character. But if you're using the char array to just hold characters, and not to do any string manipulation, then it'll be ok as long as you have a variable that holds how many characters are in the char array. Here's some examples:
    Code:
    char sword[4];
    sword[0] = '1';
    sword[1] = '2';
    sword[2] = '3';
    sword[3] = '4';
    /* We know it's 4 characters long, but strlen() does not. */
    printf("%i\n", strlen(sword));
    But if we go like this:
    Code:
    char sword[5];
    sword[0] = '1';
    sword[1] = '2';
    sword[2] = '3';
    sword[3] = '4';
    sword[4] = '\0';
    /* It knows the length of the string is 4 characters long!*/
    printf("%i\n", strlen(sword));

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >the book i read told me that to create an array, you need to put the number of 'elements' in the [...].
    That's reasonable advice.

    >what is the 5th element (sword[4]) used for?
    Breaking programs. The trick is understanding that C lets you do stupid things. Array indexing is a very low level operation (almost always unchecked) equivalent to adding an offset to an address. For example, the compiler might come up with this for sWord[5]:
    Code:
    0x12345 + (5 * sizeof(char))
    But don't try to figure out what happens when you index an array out of bounds, it could be anything. Just don't do it.
    My best code is written with the delete key.

  6. #6
    ---
    Join Date
    May 2004
    Posts
    1,379
    Code:
    sWord[0] = 'T';
    sWord[1] = 'E';
    sWord[2] = 'S';
    sWord[3] = 'T';
    sWord[4] = '/0';
    your problem is '/'0' should be '\0'
    but you can leave the last element alone anyway, the compiler will fill it for you.

  7. #7
    Registered User
    Join Date
    Sep 2004
    Posts
    719
    Quote Originally Posted by sand_man
    your problem is '/'0' should be '\0'
    but you can leave the last element alone anyway, the compiler will fill it for you.

    make sure you read your warnings as you would error messages - typically, if you don;t know what a warning means, you better find out. you should have gotten one saying something like "Warning, unknown character sequence"
    i seem to have GCC 3.3.4
    But how do i start it?
    I dont have a menu for it or anything.

  8. #8
    /*enjoy*/
    Join Date
    Apr 2004
    Posts
    159
    posted sand_man
    Code:
    
    >your problem is '/'0' should be '\0'
    

    i think , you can use
    Code:
    NULL

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    Don't do as enjoy suggests

    NULL is not the same thing as '\0'
    http://www.eskimo.com/~scs/C-faq/q5.9.html
    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.

  10. #10
    /*enjoy*/
    Join Date
    Apr 2004
    Posts
    159
    i know that but
    Code:
    char ch[]={'s','s','s',NULL};
    printf("%s\n",ch);

    compiling >>>>

    sss

  11. #11
    Registered User
    Join Date
    Aug 2003
    Posts
    288
    k, thanks everyone for the replies, i know i shudnt use NULL to terminate a string.. i beleive its only for pointers? also, the '/0' was a typo, i meant '\0'

    anyway, if i declare a string, i dont HAVE to null terminate it, right? if im going to use it to store data and if i know its length?

    by the way, Sebastiani, thats a nice piece of code in your sig, i like how it draws the S
    Last edited by X PaYnE X; 01-09-2005 at 07:00 AM.

  12. #12
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >i know that but
    void main and fflush(stdin) work when I try them, but does that make it right? No. Please refrain from answering questions until you actually know the answers.

    >if i declare a string, i dont HAVE to null terminate it, right?
    Right. However, if you intend to use it as a C-style string then you do because code that works with such a string representation expects null termination.

    >if im going to use it to store data and if i know its length?
    Then you're stuck with loops or custom functions for printing and other operations. By the way, don't forget that that a string has two distinct lengths: the number of characters in the string, and the size of your memory.
    My best code is written with the delete key.

  13. #13
    Registered User
    Join Date
    Aug 2003
    Posts
    288
    im assuming the string will have a fixed number of characters so ill just need to use the size of memory.. well i guess that about answers my question, thanks for all your help everyone

  14. #14
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    enjoy, pease stop spamming, and learn to use the board's formatting tags properly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Mutli dimensional Array question.
    By fatdunky in forum C Programming
    Replies: 6
    Last Post: 02-22-2006, 07:07 PM
  2. Array of Structs question
    By WaterNut in forum C++ Programming
    Replies: 10
    Last Post: 07-02-2004, 02:58 PM
  3. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM