Thread: problems switching arrays

  1. #1
    Registered User stillwell's Avatar
    Join Date
    Aug 2004
    Posts
    80

    problems switching arrays

    Im trying to switch the values of 2 arrays, but the output is completely wrong.

    Code:
    #include <iostream>
    
    using namespace std;
    
    void test(int a[], int b[], int antal)
    {
    int c =0;    
    
    for (int i =0; i <= antal; i++)
        {
        c = a[i];
        a[i] = b[i];
        b[i] = c;
        } 
    }
    
    int main()
    {
    int a[1, 9, 8, 6], b[5, 5, 5, 5], antal =4;
    
          for(int i =0; i < 4; i++)
          cout << a[i];
          
          cout << endl;
          
          for(int i =0; i < 4; i++)
          cout << b[i];
          
          test (a, b, 4);
          
          for(int i =0; i < 4; i++)
          cout << a[i];
          
          cout << endl;
          
          for(int i =0; i < 4; i++)
          cout << b[i];
    
              return 0;
    }
    Can anyone help me see where the error lies?

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Code:
    a[1, 9, 8, 6], b[5, 5, 5, 5]
    Never seen that one before.
    Sent from my iPadŽ

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >for (int i =0; i <= antal; i++)
    Here you're going one past the end of the array. So:
    Code:
    for (int i =0; i < antal; i++)
    >int main()
    >{
    >int a[1, 9, 8, 6], b[5, 5, 5, 5], antal =4;

    The proper way to initialize arrays is:
    Code:
    int main()
    {
       const int antal = 4;
       int a[antal] = {1, 9, 8, 6}, b[antal] = {5, 5, 5, 5};
    Last edited by swoopy; 02-27-2006 at 12:56 PM. Reason: Forgot int on const declaration

  4. #4
    Registered User stillwell's Avatar
    Join Date
    Aug 2004
    Posts
    80
    psh, that's right. It's been a while

    Thanks for the help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problems with arrays
    By vikingcarioca in forum C Programming
    Replies: 4
    Last Post: 03-31-2009, 07:21 AM
  2. 2D arrays, strcpy and strcmp Problems
    By Windu102 in forum C Programming
    Replies: 3
    Last Post: 08-23-2008, 01:00 AM
  3. Dynamic (Numeric) Arrays
    By DavidB in forum C++ Programming
    Replies: 5
    Last Post: 05-03-2006, 07:34 PM
  4. Problems with Strings and Arrays.
    By SlyMaelstrom in forum C++ Programming
    Replies: 13
    Last Post: 04-15-2005, 02:13 PM
  5. Help!!! Problems with arrays.
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 05-08-2002, 08:21 PM