Thread: Help with a 2D Array in C

  1. #1
    Registered User Unee0x's Avatar
    Join Date
    Nov 2011
    Posts
    12

    Help with a 2D Array in C

    I have been working on a 8x8 Array for a day or two, and this what I have
    Code:
    #include <stdio.h>
    int main()
    {
    
    
      int  x,y;
    
    
      for(y=1;y<=8;y++){
        for(x=1;x<=8;x++){
          int Board[8][8];
    
    
     printf(" %d", Board[8][8]);
        }
            printf("\n");
      }
    
    
      return 0;
    }
    But instead of getting a 1-8 count in columns and rows, all i get is zeros like this:
    Code:
     0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0
    please help me understand how to get a true 8X8 matrix

    ps
    I am not looking for the answer, only the way to it....

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    You need to initialize your array at the top below main, not inside your for loop. Right now you are not changing the value of your array or the indexing of it. Look at how you have hardcoded the indexes. Instead of that you can use x and y representing your rows and columns. P.S. You should start x and y off at 0 and < 8 .

  3. #3
    Registered User Unee0x's Avatar
    Join Date
    Nov 2011
    Posts
    12
    First , Thank You.
    Do you mean like this:
    Code:
    #include <stdio.h>
    int main()
    {
    
    
      int  x,y;
      int Board[y][x];
      for(y=1;y<=8;y++){
        for(x=1;x<=8;x++){
     printf(" %d", Board[8][8]);
        }
            printf("\n");
      }
    
    
      return 0;
    }
    if so, I get the same results..

  4. #4
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Few things:
    1. You are fine with the hard coding in your initialization of int board[8][8].
    2. Your for loop should start at 0 and go to < 8, for(x=0;x<8... same for y. In C arrays start indexing at 0.
    3. You also need to display using your x and y indexes. printf(... board[x][y].

    You havnt given any actual values to your array so you will find that it will be a bunch of random numbers when you do print it.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    for(r=0;r<8;r++) {
       for(c=0;c<8;c++) {
          board[r][c]= r;
       }
    }
    
    for(r=0;r<8;r++) {
       for(c=0;c<8;c++) {
          printf("%d ",board[r][c]);
       }
       printf("\n");
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 03-20-2012, 08:41 AM
  2. Replies: 9
    Last Post: 08-23-2010, 02:31 PM
  3. Replies: 9
    Last Post: 04-07-2010, 10:03 PM
  4. Replies: 1
    Last Post: 10-21-2007, 07:44 AM
  5. Replies: 6
    Last Post: 11-09-2006, 03:28 AM