Thread: Weird output loop+array.

  1. #1
    Novice.
    Join Date
    Oct 2005
    Posts
    88

    Weird output loop+array.

    I've got the following function:
    Code:
    void deck()
    {
    	int cards[14][4];
    	int a;
    	int b;
    	for (b = 0; b < 4;b++)
    	{
    		for (a = 1; a < 15; a++)
    		{
    			cards[a][b] = a;
    			printf("%d\n",cards[a][b]);
    		}
    	}
    return;
    }
    The output is:
    Code:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    -304991592
    I notice it sort of crashes in the 3rd time it does the b loop. At least it puts a silly value in cards[14][3]
    and then stops doing the loop.

    Could anybody help?

    Thank You.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Recall that array indices start from 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
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    int cards[14][4];
    Valid indicies for the first dimension are from 0 through 13 (inclusive). You are going from 1 to 14.
    "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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with output from array
    By jaw24 in forum C++ Programming
    Replies: 4
    Last Post: 04-05-2007, 09:16 PM
  2. for loop with sort issues
    By redmondtab in forum C Programming
    Replies: 10
    Last Post: 10-09-2006, 10:36 AM
  3. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  4. Ex. 2-4 KnR (2nd ed.) loop && array handling
    By olbas in forum C Programming
    Replies: 2
    Last Post: 03-23-2004, 11:07 PM
  5. for loop to create an array of objects
    By Shadow12345 in forum C++ Programming
    Replies: 9
    Last Post: 05-03-2002, 06:26 PM