Cannot understand 'char' array text problem.

This is a discussion on Cannot understand 'char' array text problem. within the C++ Programming forums, part of the General Programming Boards category; Hi First off, nice to be here. A really good place for starters and advance users alike. I have begun ...

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    5

    Cannot understand 'char' array text problem.

    Hi

    First off, nice to be here. A really good place for starters and advance users alike. I have begun to refresh my C++ skills after 6 years of electronics study at college. Here is the problem:

    This program takes a text in the char array "test" and stores alternate characters in two different char arrays a and b (even and odd positions). (this may not be clear, im really tired) but the code explains in detail.

    I am having trouble in getting the output after the 'for' loop. The 'for' loop that supposedly does the main work and also displays the content of two arrays.

    The next time I try to display the arrays, its a different output.


    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    //Initializing two empty (?) char arrays to store the alternate chars from
    //the test string.
    
    char a[]="";
    char b[]="";
    
    int main()
    {
        // Initialization of the test srting. using no space to make it simple for now,
        // but spaces also work
        char test[]="HelloWorldHowAreYou";
        cout << "The string is " << test << " of size " << sizeof(test) << endl;
    
        // Loop test to output the string "test" using loop.
        // Used unsigned int to avoid any warnings in comparisson.
        cout << "\nLoop Test: \n";
        for (unsigned int j=0;j<sizeof(test);j++)
        {
            cout << test[j] << " ";
        }
        cout << "\n\n\n";
    
        // The main program to store alternate chars in two different char arrays.
        // Loop using unsigned int. The output of this process is correct!
        for (unsigned int i=0;i<sizeof(test);i++)
        {
            a[i]=test[(2*i)];
            b[i]=test[(2*i)+1];
    
            cout << "a " << i << " is: " << a[i] << endl;
            cout << "b " << i << " is: " << b[i] << endl;
    
        }
        cout << "\n\n\n";
    
        // This is where it gets really annoying, I dont get a meaningful output.
        // Even if the previous 'for' loop correctly places the chars alternatively
        // The output given here is completely incorrect. Example: a[3] is supposed to be
        // "o" and b[3] = "r", but the output is mixed up.
        // I do realize it could be because of the way arrays work, but please
        // explain. I would like to understand this better.
    
        cout << "The output after the storing of alternate chars in a,b. \n\n";
    
        for (unsigned int k=0;k<sizeof(test);k++)
        {
            cout << "a " << k << " is: " << a[k] << endl;
            cout << "b " << k << " is: " << b[k] << endl;
        }
    
        //cout << "\n" << a << b << endl;
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Mar 2010
    Posts
    109
    Code:
    a[i]=test[(2*i)];
    b[i]=test[(2*i)+1];
    This is going to read past the bounds of your array.

    You probably want something like:
    Code:
    int sizeA, sizeB;
    sizeA = sizeB = 0;
    for (unsigned int i=0; i<sizeof(test); i++)
    {
    	if( i % 2 == 0 )
    	{
    		a[sizeA] = test[i];
    		sizeA++;
    	}
    	else
    	{
    		b[sizeB] = test[i];
    		sizeB++;
    	}
    }

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Code:
    char a[]="";
    char b[]="";
    Try printing out the size of those arrays and see how big they are.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    Apr 2010
    Posts
    5
    Thankyou @syzy and @hk_

    @syzy: I tried your code but its giving kind of the same problem. Here is the code with your edit and its output::::

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    //Initializing two empty (?) char arrays to store the alternate chars from
    //the test string.
    char a[] = "";
    char b[] = "";
    
    int main()
    {
        // Initialization of the test srting. using no space to make it simple for now,
        // but spaces also work.
        char test[] = "HelloWorldHowAreYou";
        cout << "The string is " << test << " of size " << sizeof(test) << endl;
    
        // Loop test to output the string "test" using loop.
        // Used unsigned int to avoid any warnings in comparisson.
        cout << "\nLoop Test: \n";
        for (unsigned int j=0; j<sizeof(test); j++)
        {
            cout << test[j] << " ";
        }
        cout << "\n\n\n";
    /*
        // The main program to store alternate chars in two different char arrays.
        // Loop using unsigned int. The output of this process is correct!
        for (unsigned int i=0;i<sizeof(test);i++)
        {
            a[i]=test[(2*i)];
            b[i]=test[(2*i)+1];
    
            cout << "a " << i << " is: " << a[i] << endl;
            cout << "b " << i << " is: " << b[i] << endl;
    
        }
        cout << "\n\n\n";
    
    */
    
        //// Your code @syzy::::::
    
        cout << "The new process and output after the storing of alternate chars in a,b. \n\n";
    
        int sizeA, sizeB;
        sizeA = sizeB = 0;
        for (unsigned int i=0; i<sizeof(test); i++)
        {
            if( i % 2 == 0 )
            {
                a[sizeA] = test[i];
                sizeA++;
            }
            else
            {
                b[sizeB] = test[i];
                sizeB++;
            }
        }
    
    
        //The display of arrays. Here using siezeof "test" just to be sure. Otherwise sizeofA = 10 (half of 20, this much is correct) 
        //and sizeof "a" is 4 (?!)
    
        for (unsigned int k=0;k<sizeof(test);k++)
        {
            cout << "a " << k << " is: " << a[k] << endl;
            cout << "b " << k << " is: " << b[k] << endl;
        }
    
        //cout << "\n" << a << b << endl;
    
    
        return 0;
    }
    
    
    The Output:
    
    The string is HelloWorldHowAreYou of size 20
    
    Loop Test:
    H e l l o W o r l d H o w A r e Y o u
    
    
    The new process and output after the storing of alternate chars in a,b.
    
    a 0 is: H
    b 0 is: l
    a 1 is: l
    b 1 is: o
    a 2 is: o
    b 2 is: o
    a 3 is: o
    b 3 is: l
    a 4 is: l
    b 4 is: H
    a 5 is: H
    b 5 is: w
    a 6 is: w
    b 6 is: r
    a 7 is: r
    b 7 is: Y
    a 8 is: Y
    b 8 is: u
    a 9 is: u
    b 9 is:
    a 10 is:
    b 10 is:
    a 11 is:
    b 11 is:
    a 12 is:
    b 12 is:
    a 13 is:
    b 13 is:
    a 14 is:
    b 14 is:
    a 15 is:
    b 15 is:
    a 16 is:
    b 16 is:
    a 17 is:
    b 17 is:
    a 18 is:
    b 18 is:
    a 19 is:
    b 19 is: ▒
    
    Process returned 0 (0x0)   execution time : 0.167 s
    Press any key to continue.
    @hk_
    Yea, just after initialization of arrays a and b, their size is just 1. I guess(!) this is the size of the first element of their pointed value since nothing is stored in them. I am slowly beginning to understand the working of pointers but this program I wrote still baffles me.
    Last edited by xheavenlyx; 04-22-2010 at 03:27 PM.

  5. #5
    Registered User
    Join Date
    Mar 2010
    Posts
    109
    First, fix the issue that hk mentioned. Declaring
    Code:
    char a[] = "";
    char b[] = "";
    Doesn't work for your purpose. You are trying to declare variable-sized arrays, but you can't do it that way. You have to give it some fixed length:

    Code:
    char a[256] = "";
    char b[256] = "";

  6. #6
    Registered User
    Join Date
    Apr 2010
    Posts
    5
    Oh yes, it worked!

    I put in '50' and it worked. It also works with 10. But when I go down even one, like 9, It gives the first few characters wrong and then WorldHowAreYou is correct.

    Understood, thank you so much!
    Ok, now Ill go on to read the pointers chapter to understand this better. But if you got time could you briefly explain why this is so? I mean, variable array means flexible array. Is there another way to NOT declare an initial size and still make it work (using pointers or such?). Or is it because of a safety reason (mem constrints for infinitely growing arrays)?

  7. #7
    Registered User
    Join Date
    Mar 2010
    Posts
    109
    Glad you got it. The reason it doesn't work when you go less than 10 is probably the same reason why it wasn't working when you declared your arrays without a fixed length. You are trying to write past the bounds of the memory that you told the compiler to allocate. This will cause all kinds of problems.

    If you say you want char a[10], then the program sets up 10 consecutive bytes of memory for you to use, which you access through the variable 'a'. It's technically a pointer to the beginning of that sequence of memory.

    You have to be careful when accessing arrays, because they basically are pointers. If you tell it you want what is at a[1024] but you only made a 12 bytes long, then you are accessing unknown memory. For instance, your last for loop that displays the two arrays a and b, counts up too high. 'test' is longer than a or b so by the time you reach the end of test, it's already gone past the bounds of a and b (assuming you declared them with a length shorter than test).

    There is a way to allocate memory dynamically, but that will be for later. I'm sure you will learn about it soon, it deals with using the new operator and pointers.

    Edit:

    If you want to read up on dynamic allocations: http://www.cprogramming.com/tutorial...llocation.html
    I'm sure it will explain things better than I can.
    Last edited by syzygy; 04-22-2010 at 04:06 PM.

  8. #8
    Registered User
    Join Date
    Apr 2010
    Posts
    5
    Great explanation! Now it will be easier to get into pointers and their advance uses.

    Ill take a look at the link tomorrow and practice. Thanks again.

  9. #9
    Registered User
    Join Date
    Apr 2010
    Posts
    10
    It seems to me that hte logic you have applied to store even and odd positions character is making the error.

    Just try this out for storing even and odd characters:

    insert
    Code:
      
    
    int n1,n2;
       n1=0;
       n2 = 0;
        for (int i=0; i<sizeof(test); i++)
        {
            if( i % 2 == 0 )
            {
                a[n1] = test[i];
                n1++;
            }
            else
            {
                b[n2] = test[i];
                n2++;
            }
        }

  10. #10
    Registered User
    Join Date
    Apr 2010
    Posts
    5
    Thanks @MR. AB.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to use FTP?
    By maxorator in forum C++ Programming
    Replies: 8
    Last Post: 11-04-2005, 02:17 PM
  2. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  3. Putting strings into an array from a text file.
    By JLan in forum C Programming
    Replies: 5
    Last Post: 11-20-2003, 06:34 PM
  4. Replies: 6
    Last Post: 10-21-2003, 09:57 PM
  5. Ok, Structs, I need help I am not familiar with them
    By incognito in forum C++ Programming
    Replies: 7
    Last Post: 06-29-2002, 09:45 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21