简体   繁体   中英

2D array get filled with garbage when passed as a pointer to function

I have this array declared inside my main() function:

int   VISITED[9][9]={{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,0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0,0}};

it is getting passed to a function called qneighbor with the line

qneighbor (5,5,1, 0, &pawn_positions, &PAWNS, WALLH, WALLV, &VISITED);

qneighbor signature looks like this:

CELL* qneighbor( int root_row, int root_col, int p, int dist, struct GameTable* PAWN_POSITIONS, int (*PAWNS)[9][9], int WALLH[8][9], int WALLV[9][8], int (*VISITED)[9][9]){...}

However, when debugging, I see that after the fifth line, it is getting filled with garbage , immediately after being passed to qneighbor (before any command is executed). What could be going wrong?

It seems there isn't a particular problem in your code.
By the way, as bcsanches mentioned, qneighbor 's parameter int (*VISITED)[9][9] is a pointer to int[9][9] .
In order to access its elements, VISITED itself has to be dereferred as (*VISITED)[ i ][ j ] .
If you write VISITED[ i ][ j ] , it represents a pointer, not an int.
So, if you write printf( "%d", VISITED[i][j] ) to confirm the value, it prints a pointer value(address) as an int, and it appears to be a garbage.

array index out of bounds
keep index's < 9

you do not need to use pointers to change the array, arrays are passed by reference, so, change to:

CELL* qneighbor( int root_row, int root_col, int p, int dist, struct GameTable* PAWN_POSITIONS, int PAWNS[9][9], int WALLH[8][9], int WALLV[9][8], int VISITED[9][9]){...}

and call it using:

qneighbor (5,5,1, 0, &pawn_positions, PAWNS, WALLH, WALLV, VISITED);

On your code, you are actually creating a array of pointers...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM