Thread: Confused.. Help please?

  1. #1
    Banned
    Join Date
    May 2004
    Posts
    55

    Confused.. Help please?

    Since I learned arrays a couple of days ago I got really annoyed when this program didn't worked, could anyone give me a hint?
    Code:
    #include <iostream.h>
    #include <cstdio>                //required to pause
    using namespace std;         //required to pause
    int main()
    {
        int array[4] = { 10, 20, 30, 40 };
        cout<<array[1]<<endl;
        cout<<array[2]<<endl;
        cout<<array[3]<<endl;
        cout<<array[4]<<endl;
        getchar();    //pause
        getchar();    //pause
    return 0;
    }
    What happened is, instead of outputting
    Code:
    10
    20 
    30 
    40
    it outputted
    Code:
    20 
    30 
    40 
    4370432
    Last edited by Noxir; 07-22-2004 at 01:54 AM.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > int array[4] = { 10, 20, 30, 40 };
    This declares an array from 0 to 3. There is no index 4.

    So:
    Code:
        cout<<array[0]<<endl;
        cout<<array[1]<<endl;
        cout<<array[2]<<endl;
        cout<<array[3]<<endl;

  3. #3
    Banned
    Join Date
    May 2004
    Posts
    55
    Oh thnx!

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    And if you've learned for-loops, you can print the array like this:
    Code:
    for (int i=0; i<4; i++)
        cout<<array[i]<<endl;

  5. #5
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    classic example of accessing an array outside it's boundry.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Confused
    By jeev2005 in forum C Programming
    Replies: 5
    Last Post: 06-01-2006, 02:04 PM
  2. Confused
    By (TNT) in forum C# Programming
    Replies: 1
    Last Post: 11-23-2005, 04:49 PM
  3. why wont this compile?!? :confused:
    By jdude in forum C++ Programming
    Replies: 5
    Last Post: 11-25-2004, 01:13 AM
  4. confused.. in selecting my line of deapth
    By jawwadalam in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 05-04-2003, 01:21 PM
  5. Extern Question, really confused
    By SourceCode in forum C Programming
    Replies: 10
    Last Post: 03-26-2003, 11:11 PM