global 2D array values changing between modules

Viewed 40

I have a 2D extern array "the_board[17][25]". I am fairly new to C and believe I have some linking issue. in my board.c file I initialized the board, giving every cell a value. when calling the board in my other functions, the values change, even though I have made no edits to the array since initializing it.

header file to declared array:

#define BOARD_SIZE_X 25
#define BOARD_SIZE_Y 17
extern int the_board[BOARD_SIZE_Y][BOARD_SIZE_X];
#define DA 0            /* disallowed */
#define RE 1            /* red */
#define GR 2            /* green */
#define EM 7            /* empty */

board.c file containing initialization:

#include "my_header.h"
int the_board[BOARD_SIZE_Y][BOARD_SIZE_X] = {
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7},
    {0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0},
    {0, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 0},
    {0, 0, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 0, 0},
    {0, 0, 0, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 0, 0, 0},
    {0, 0, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 0, 0},
    {0, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 0},
    {0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0},
    {7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};

Sorry for the large block of code it has to be manually defined. This is where the problem I run into. When calling the_board[][], the values become screwed up. For an example this is what happens when I print the_board[BOARD_SIZE_Y][BOARD_SIZE_X] in main.c:

img of array: https://i.stack.imgur.com/KLQqT.png

#include "my_header.h"
int main() {
int i, j;
int the_board[BOARD_SIZE_Y][BOARD_SIZE_X];

    for (i = 0; i < BOARD_SIZE_Y; i++){
        for (j = 0; j < BOARD_SIZE_X; j++) {
            printf(" %d ", the_board[i][j]);
        }
    }
return 0;
}
1 Answers

You have one initialised global the_board, defined in board.c.
You have one non-initialised local the_board defined inside main().
That second one hides the first one.
Delete the line which defines it, i.e.

int the_board[BOARD_SIZE_Y][BOARD_SIZE_X];
Related