0

我试图实现一个搜索多维数组的函数,找出其中是否有值,然后移动该函数。我的搜索功能

 bool search(int value, int values [][d], int n)
 {   
     bool In = false;
 //d is an it that is the maximum length and height 
 //e.g 3x3 or 4x4 as in the image below

 for(int row=0; row<d; row++)
 {  
    for(int col=0; col<d; col++)
    {   
        if(values[row][col] == value)
        {   
            //checking if this loop is executed
            printf("EXECUTED!! :) \n");
            In=true;
        }
         printf("Row:%i & Col%i: %i \n",row,col,values[row][col]);

    }
 }

//Usleep for debugging purpouses 
// as another function clears the screen
 usleep(50000000);

 if(In==true){return true;}
 if(In==false){return false;}


}

这是打印的内容,这对于打印上面的 4x4 框很奇怪,我使用了相同的数组,并且搜索功能无论如何都不会改变数组。这是我的“移动”功能

bool move(int tile)
{   

if(search(tile,board,d))
{
    printf("please execute this code pretty please clang\n");
    return true;
}
else
{   
    printf("NOO\n");
    return false;
}

}

这是首先初始化变量的函数

void init(void)
{
    bool even;

if((d & 1) == 0)
{
    even = true;
}
else
{
    even = false;
}

int value = d*d - 1;

for(int row =0; row<d; row++)
{
    for(int col=0; col<d; col++)
    {
        board[row][col]=value;
        value--;
    }
}

  //for this game to work if d is even the values of the third
  // and second last arrays must be switched
  if(even==true)
    {  
        int temp = board[d-1][d-2];
        board [d-1][d-2] = board[d-1][d-3];
        board [d-1][d-3] = temp;

    }
}

编辑:这是完整代码的 pastebin http://pastebin.com/yS8DDEqZ 注意 Cs50 是一个自定义库,由 im 类实现,它定义了一个字符串,一个辅助函数,用于获取用户输入 GetInt() 等。

4

1 回答 1

1

好的,我明白了。

您肯定在使用符合 C99 的编译器,它允许可变长度数组。

您的代码中的相关摘录:

#define MAX 9
int board[MAX][MAX]; // <- board is an int[9][9]

int d; // <- d is a global variable

bool search(
    int value,
    int values[MAX][d], // <- tells compiler to handle values as int[9][d]
    int n); 

// from within init()
for(int row =0; row<d; row++)
for(int col=0; col<d; col++)
    board[row][col]=value--; // <- board inited as an int[9][9]

固定大小的数组是一大块连续的内存,行一个接一个地存储。

例子:

int a[2][3]存储为 6 个整数,对应于:

a[0][0]
a[0][1]
a[0][2]
a[1][0]
a[1][1]
a[1][2]

这里board的内存布局是 9x9 :

000000000
111111111
222222222
333333333
444444444
555555555
666666666
777777777
888888888

或在线性内存中:

000000000111111111222222222333333333444444444555555555666666666777777777888888888

现在如果 d 为 4,如您的屏幕截图所示,搜索功能将认为其布局为:

0000
1111
2222
3333
4444
5555
6666
7777
8888

或在线性内存中:

000011112222333344445555666677778888

您的 init 函数使用 9x9 布局,因此它的值如下所示:

15 14 13 12 x x x x x
11 10  9  8 x x x x x etc.

但是您的搜索功能将它们读取为:

15 14 13 12
 x  x  x  x 
 x 11 10  9
 8  x  x  x 
etc.

基本上,您在原型中为数组声明的结构search()与其声明不一致。

您鲁莽地违反了 C 鲜为人知的黄金法则之一:
始终保持函数参数和数组声明的一致。
C 用一个神秘的错误惩罚了你。

阅读我的这篇小文章了解更多详情。

于 2014-01-28T22:13:54.447 回答