Filling up a 2D (or 3D) array.

This is a discussion on Filling up a 2D (or 3D) array. within the C Programming forums, part of the General Programming Boards category; How am I supposed to fill up a 2D array? I've managed to get away with the following: Code: #include ...

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

    Filling up a 2D (or 3D) array.

    How am I supposed to fill up a 2D array?
    I've managed to get away with the following:
    Code:
    #include <stdio.h>
    
    int main()
    {
    int board[3][3] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
    int a, b;
    int i;
    int j;
    for (i = 0;i < 3; i++)
        {
         for (j = 0; j < 3; j++)
         {
          printf("&#37;d", board[i][j]);
         }
         printf("\n");
        }
    printf("Input a: ");
    scanf("%d", &a);
    printf("Input b: ");
    scanf("%d", &b);
    board[a][b] = 1;
    
    for (i = 0;i < 3; i++)
        {
         for (j = 0; j < 3; j++)
         {
          printf("%d", board[i][j]);
         }
         printf("\n");
        }
    
    getchar();
    getchar();
    }
    It works fine, but is it correct?



    Thank You!

    (I mean with pre-set numbers, I understand that you could fill it with zeros just by using a loop.)
    Last edited by omnificient; 01-20-2008 at 01:04 PM. Reason: Needed to clarify a bit.

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    you have a 3X3 int array, so you need 3 entries (rows), each 3 (columns) wide- for a total of 9 constants. You have the 9 constants, but not in row/column sets.

    Code:
     
    int board[3][3] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
    To init an int[3] array, you would code:

    Code:
    int board[3] = {0,0,0}  ;
    To init an int [2][2] array, you would code:

    Code:
    int board[2][2] = { 
                      {0,0} , 
                      {0,0} 
                      }
    Get it?

    Todd

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 2D array of threads?
    By shorinhio in forum C Programming
    Replies: 2
    Last Post: 01-04-2007, 04:02 PM
  2. passing/pointing to a 2d array
    By jamie85 in forum C Programming
    Replies: 7
    Last Post: 10-28-2005, 11:16 PM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10:54 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 08:48 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 09:31 AM

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