Reputation: 199
I need to declare a 2d array to represent the size of chess-board. However, I'm having a trouble understanding how would I actually calculate the width and the length of the board. I would like to know how could I calculate size of the rows and columns of my 2d array
Say, int boardSize[5][5]
?
int main()
{
int boardSize[5][5];
int boardWidth=?
int boardHeight =?
createBoard(boardWidth, boardHeight);
}
int createBoard(int width, int height)
{
// code that actually creates board //
}
Sorry, for not being specific in the begging. So, here I need to calculate boardwidth and boardheight variables? How do I do that from the declared array above. Thank you!
Upvotes: 6
Views: 21133
Reputation: 213711
This is easily fixed with the removal of all mysterious magic numbers from your code.
#define BOARD_WIDTH 8
#define BOARD_HEIGHT 8
square_t board [BOARD_WIDTH][BOARD_HEIGHT];
createBoard (board, BOARD_WIDTH, BOARD_HEIGHT);
void createBoard (square_t* board, int boardWidth, int boardHeight)
{
}
Upvotes: 0
Reputation: 4589
printf("Size of the board in bytes %d\n", sizeof(boardSize));
printf("Size of column size in bytes %d\n", 5*sizeof(int));
printf("Size of row in bytes %d\n", 5*sizeof(int));
If you want leave the board as statically allocated the declare it as global like,
static int board[5][5];
Then traverse it in your "createBoard" method(I hate Hungarian notations) for correct initialization :
for(i = 0; i < hight; i++)
for(j = 0;j< width; j++)
board[i][j] = <initialization stuff>
or you can dynamically allocate it in your createBoard() method. In that case do not declare as local variable for main.
int * createBoard(int hight, int width){
int * board;
if(board = malloc(sizeof(int) * hight * width))
return board;
return NULL;
}
in main() you can do something like this:
int * board = createBoard(5,5);
if(!board)
printf("Allocation failure \n");
exit(EXIT_FAILURE);
Upvotes: 0
Reputation: 78903
boardSize[0]
gives you the first row of the matrix, boardSize[0][0]
the first of its elements. So the quantities you are looking for are sizeof boardSize/ sizeof boardSize[0]
and sizeof boardSize[0]/ sizeof boardSize[0][0]
.
BTW: use size_t
as a type for sizes, not int
.
Upvotes: 8
Reputation: 399803
If you say
int boardSize[5][5];
that gives you a 2D array of integers, 5 by 5 in size. So it will have 5 rows of 5 columns each, for a total of 25 integers.
Upvotes: 0