简体   繁体   English

无法将数组传递给递归函数C ++

[英]Having trouble passing array to recursive function c++

When I run the function "check_row" within itself, there is a problem with the way I'm trying to pass in the array "sudoku_temp", but I'm not sure what I'm doing wrong. 当我在内部运行函数“ check_row”时,尝试传递数组“ sudoku_temp”的方式存在问题,但是我不确定自己做错了什么。 Am I missing something? 我想念什么吗?

int check_row(int j_position, int generated_value, int sudoku_temp[][9]){
for (int i_position = 0; i_position < 9; i_position++)
{
    if (generated_value == sudoku_temp[i_position][j_position])
    {
        generated_value = generate_number();
        check_row(j_position, generated_value, sudoku_temp[][j_position]);
    }
    else
        return generated_value;

}

} }

To clarify, the problem is when I try to call on the function within itself. 要澄清的是,问题是当我尝试调用自身内部的函数时。 Thanks. 谢谢。

use a variable instead of fixed length like 9. since in recursion the argument may be different. 使用变量而不是固定长度(如9),因为递归中的参数可能不同。

int check_row(int j_position, int generated_value, int sudoku_temp[][n])
{
    for (int i_position = 0; i_position < n; i_position++)
    {
        if (generated_value == sudoku_temp[i_position][j_position])
        {
            generated_value = generate_number();
            check_row(j_position, generated_value, sudoku_temp[][j_position]);
        }
        else
            return generated_value;

    }
}

When you want to extract a value from an array, you cannot leave empty brackets like you did. 当您要从数组中提取一个值时,您不能像您一样留空括号。 On the other hand, the function prototype looks similar and it's perfectly fine. 另一方面,函数原型看起来很相似,而且很好。 Why? 为什么?

int sudoku_temp[][9] // A 2D array of integers second dimension of which is of size 9

Or in other words, an array (of unknown size) of arrays of size 9. We are not telling the compiler how big the array really is and we don't have to in this case as it is simply given to us as an argument. 或者换句话说,是一个大小为9的数组(大小未知)。我们没有告诉编译器数组的实际大小,在这种情况下我们不必这样做,因为它只是作为参数提供给我们的。

When accessing elements on the other hand, we cannot leave empty brackets for a simple reason: we want to access an element and the compiler has to know which one. 另一方面,在访问元素时,由于简单的原因,我们不能留空括号:我们要访问元素,并且编译器必须知道哪个元素。 Cutting to the chase - removing the empty [] should solve your problem. 顺其自然-删除空的[]应该可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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