Row 2d Array / Column Length C

I need to declare a 2d array to represent the size of a checkerboard. However, I had problems understanding how I can calculate the width and length of the board. I would like to know how I could calculate the size of the rows and columns of my 2d array

Tell me, 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 begging. So, here I need to calculate the bandwidth and variable variables? How to do this from the declared array above. Thanks!

+6
source share
4 answers

boardSize[0] gives you the first row of the matrix, boardSize[0][0] first of its elements. So the quantity you are looking for is sizeof boardSize/ sizeof boardSize[0] and sizeof boardSize[0]/ sizeof boardSize[0][0] .

BTW: use size_t as a type for sizes, not int .

+8
source

If you say

 int boardSize[5][5]; 

which gives you a 5 by 5 2D array of integers. Thus, it will have 5 rows of 5 columns each, for a total of 25 integers.

0
source
 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 to leave the board as statically allocated, declare it global,

 static int board[5][5]; 

Then move it to your createBoard method (I hate Hungarian notation) for proper initialization:

 for(i = 0; i < hight; i++) for(j = 0;j< width; j++) board[i][j] = <initialization stuff> 

or you can dynamically distribute it in your createBoard () method. In this case, do not declare the local variable 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); 
0
source

This is easily fixed by removing all cryptic 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) { } 
0
source

Source: https://habr.com/ru/post/919675/


All Articles