这是我的(不完整)代码的一部分
int rows(int board[][9]){
int badUnits = 0, i = 0, n = 9, j, z = 0;
int (*temp)[9];
//Sort each row of 2d array
for (z; z < n; z++){
for (i; i < n; i++){
for (j = i; j < n; j++){
if (board[z][i] > board[z][j]){
temp = board[z][i];
board[z][i] = board[z][j];
board[z][j] = temp;
}
}
}
}
printf ("%d\n", temp[1][0]);
printf ("%d\n", temp[1][1]);
return badUnits;
}
该函数采用 9*9 数组。
执行打印语句时出现段错误。 我相信我的排序代码是正确的,因为它与我用于一维数组的代码类似,并且我认为其他所有内容都已正确分配。
所以罪魁祸首是我的临时变量。我已经完成并尝试为其赋值,尝试更改类型,并考虑到二维数组会衰减为指针,但实际上并不是指针。
我剩下的结论是,这是一个动态分配问题。有人可以帮我解决这个问题吗?我已经用尽了我的知识库并且陷入了困境。
澄清一下:我决定打印 temp 变量,因为我认为它可以提供一些信息。主要问题是交换不起作用,当我最初尝试打印 board[][] 时,仍然留下一个未排序的数组。我知道那 block 板就是我应该打印的。
感谢您的帮助!
最佳答案
您为 temp 分配一个 int 值
temp = board[z][i]; // Temp now is a what ever value was at
// That location in the array e.g. 42
然后,您将 temp 视为整数数组内存中的地址
temp[1][1] // treat temp as a pointer and find the integer
// 10 integers further along then temp.
有时 temp 不会被初始化(从未分配给),在这种情况下,您将得到意外的行为,具体取决于 temp 现在所在位置存储的最后一个值(我们将其称为随机数)。
您的意思是输出板上的值吗?
printf ("%d\n", board[1][0]);
printf ("%d\n", board[1][1]);
关于c - c 中的二维数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26456356/