我目前正在练习递归,这样我就可以在Tideman CS50问题中使用它.具体地说,我想学习如何使用递归遍历矩阵(2D数组).

出于练习目的,我已经创建了一个简单的3x32D数组,我想打印该数组的内容.

不幸的是,my logic breaks after the first row is successfully printed: printing subsequent elements of the array is incorrect岁.更准确地说,我的递归函数在try 打印位置为i = 1,j = 0的元素时"中断".我想知道为什么会发生这种情况.

代码:

#include <stdio.h>

void recursive_print(int lenght, int i, int j, int array[i][j]);

int main(void)
{
    int lenght = 3;
    int i = 0;
    int j = 0;
    
    int array[lenght][lenght];
    array[0][0] = 0;
    array[0][1] = 1;
    array[0][2] = 2;
    array[1][0] = 3;
    array[1][1] = 4;
    array[1][2] = 5;
    array[2][0] = 6;
    array[2][1] = 7;
    array[2][2] = 8;
    
    recursive_print(lenght, i, j, array);
    
    return 0;
}

void recursive_print(int lenght, int i, int j, int array[i][j])
{
    // Base case
    if (i == lenght - 1 && j == lenght - 1)
    {
        printf("Base case\n");
        printf("%i\n", array[i][j]);
    }

    // Recursive case(s)
    else if (j == lenght - 1)
    {
        printf("Recursive case 1\n");
        printf("%i\n", array[i][j]);
        recursive_print(lenght, i + 1, j - j, array);
    }
    else
    {
        printf("Recursive case 2\n");
        printf("%i\n", array[i][j]);
        recursive_print(lenght, i, j + 1, array);
    }
}

实际yields :

Recursive case 2
0
Recursive case 2
1
Recursive case 1
2
Recursive case 2
0
Recursive case 2
2
Recursive case 1
4
Recursive case 2
0
Recursive case 2
3
Base case
6

预期输出:

Recursive case 2
0
Recursive case 2
1
Recursive case 1
2
Recursive case 2
3
Recursive case 2
4
Recursive case 1
5
Recursive case 2
6
Recursive case 2
7
Base case
8

推荐答案

你对int array[i][j]的观点是错误的,它应该是int array[3][3],或者更优雅的array[][3].

假设array在存储器中被组织为1d.array[][3]让编译器知道在沿着一行前进时跳过3个位置(即增加第一个维度).

我认为你得到的结果很混乱,因为递归地调用函数array[1][0]告诉跳过0,当转到一个新的行时,所以实际上打印array[1][0]会指向地址array + 1 * 0 + 0 = array处的整数,所以它打印0.

array[1][1] -- skip 1
array[1][1] -> *(array + 1 * 1 + 1) = *(array + 2) = 2

array[1][2] -- skip 2
array[1][2] -> *(array + 1 * 2 + 2) = *(array + 4) = 4

array[2][0] -- skip 0
array[2][0] -> *(array + 2 * 0 + 0) = *(array + 0) = 0

array[2][1] -- skip 1
array[2][1] -> *(array + 2 * 1 + 1) = *(array + 3) = 3

array[2][2] -- skip 2
array[2][2] -> *(array + 2 * 2 + 2) = *(array + 6) = 6

C++相关问答推荐

问关于C中的指针和数组

与unions 的未定义行为

是否有任何情况(特定类型/值),类型双关在所有符合标准的C实现中产生相同的行为?

为什么写入系统调用打印的字符数不正确?

如何将不同长度的位转换成字节数组?

显式地将值转换为它从函数返回的类型的含义是什么?

在C++中使用函数指针的正确语法

限制不同类型的限定符

使用错误的命令执行程序

Flose()在Docker容器中抛出段错误

处理来自浏览器的HTTP请求

GCC奇怪的行为,有fork 和印花,有换行符和不换行符

C-try 将整数和 struct 数组存储到二进制文件中

*S=0;正在优化中.可能是GCC 13号虫?或者是一些不明确的行为?

浮动目标文件,数据段

如何使crc32的结果与cksum匹配?

当 n 是我们从用户那里获得的整数时,创建 n 个 struct 参数

如何找出C中分配在堆上的数组的大小?

为什么程序在打印每个数字之前要等待所有输入?

初始化动态分配的布尔二维数组的最佳方法是什么?