Thread: Filling 2D Array

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    1

    Filling 2D Array

    Hello!


    So here is the C code:
    Code:
    #include <stdio.h>
    int main(void)
    {
       //2D Array
       int array[2][2]; 
       int number = 1;
    
        //fill the array
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                array[j][i]=number;
                number+=1;
            }
        }
    
    /* The Code Above Is To Print The Array */
    
    //column number
    int column=0;
    for(int i=0;i<3;i++)
    {
        //column number
        printf("%d   %d   %d\n",array[column][i],array[column+1][i],array[column+2][i]);
    }
    
    }
    Can someone explain why the output is:
    0 7 8
    4 5 6
    7 8 9

    and not

    1 2 3
    4 5 6
    7 8 9


    The array is not filled incorrectly for some reason, more specifically the first row.
    The first two cycles of the for loop seem to work correctly. One if the bugs seems to occur on the third. when array[0][2] is filled with number 7, for some reason array[1][0] changes it value to 7 as well.

    Thanks in advance!

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Because you have j and i swapped inside the inner for loop.

    Code:
    array[j][i]=number;
    C is row major, and apparently you are trying to print it that way, but have column major code.
    Last edited by Adak; 03-24-2013 at 08:45 AM.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > for(int i=0;i<3;i++)
    But your array is only 2x2, so this is a large buffer overrun.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Filling an array
    By DeanWinchester in forum C Programming
    Replies: 4
    Last Post: 09-07-2012, 12:30 AM
  2. filling an array..
    By kromagnon in forum C Programming
    Replies: 3
    Last Post: 11-06-2011, 06:53 PM
  3. Filling up a 2D (or 3D) array.
    By omnificient in forum C Programming
    Replies: 1
    Last Post: 01-20-2008, 01:22 PM
  4. Filling an array
    By GCNDoug in forum C Programming
    Replies: 18
    Last Post: 04-25-2007, 02:46 PM
  5. filling an array
    By Flex in forum C Programming
    Replies: 7
    Last Post: 02-28-2002, 03:11 PM