当作为函数指针传递时,二维数组会充满垃圾
我在 main() 函数中声明了这个数组:
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}};
它被传递给一个名为 qneighbor 的函数,其中
qneighbor (5,5,1, 0, &pawn_positions, &PAWNS, WALLH, WALLV, &VISITED);
qneighbor 签名行如下所示:
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]){...}
但是,在调试时,我看到在第五行之后,它被垃圾填满了,传递给 qneighbor 后立即(在执行任何命令之前)。可能出了什么问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码中似乎没有特定的问题。
顺便说一句,正如 bcsanches 提到的,
qneighbor
的参数int (*VISITED)[9][9]
是一个指向
int[9][9]
的指针。为了访问其元素,
VISITED
本身必须被解引用为(*VISITED)[ i ][ j ]
。如果你写
VISITED[ i ][ j ]
,它代表一个指针,而不是一个int。因此,如果您编写
printf( "%d", VISITED[i][j] )
来确认该值,它将打印一个 int 类型的指针值(地址),它看起来是一个垃圾。
It seems there isn't a particular problem in your code.
By the way, as bcsanches mentioned,
qneighbor
's parameterint (*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 printsa pointer value(address) as an int, and it appears to be a garbage.
数组索引越界
保持索引的< 9
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:
and call it using:
On your code, you are actually creating a array of pointers...