'How to navigate a 1d array in a 2d manner?
I've got this sample code below. I understand cells is being made in a 1 dimensional manner, since the compiler stores 2d arrays in memory row-by-row in 1d. What I don't understand/can't visualize is how to access elements or change positions.
I know
board->cells[i + (20 * (10 - 1))] = FLAG_WALL;is used to set flags for the bottom most row. From the format it looks to be using a formula but I am unsure of what it is. The formula also seems to change for the right and left edges. (board->cells[i * 20 + 20 - 1] = FLAG_WALL;)Looking at the line
board->cells[20 * 2 + 2] = FLAG_SNAKE;it seems cell[42] is where the snake flag is spawned. What would the arithmetic look like to shift its position by 1 cell up, down, right, left? When imagining cell[42] as a part of a 1d array in memory I can't figure out the arithmetic nor the resulting cell number after a shift such as 'up'.
board_init_status_t initialize_default_board(board_t* board) {
board->width = 20;
board->height = 10;
board->cells = calloc(20 * 10, sizeof(int));
// Set edge cells!
// Top and bottom edges:
for (int i = 0; i < 20; ++i) {
board->cells[i] = FLAG_WALL;
board->cells[i + (20 * (10 - 1))] = FLAG_WALL;
}
// Left and right edges:
for (int i = 0; i < 10; ++i) {
board->cells[i * 20] = FLAG_WALL;
board->cells[i * 20 + 20 - 1] = FLAG_WALL;
}
// Add snake
board->cells[20 * 2 + 2] = FLAG_SNAKE;
return INIT_SUCCESS;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
