c - 按值返回结构每次都会给出相同的错误答案

标签 c

我正在尝试按值返回结构以查找节点在树中的位置。但是,使用包装器来简化函数调用会返回不正确的值。

相关代码:


typedef struct {
    uint16_t x;
    uint16_t y;
} coordinate_t;

coordinate_t node_pos_(uint16_t x, uint16_t y, node_t *node, node_t *find) {
    printf("%u, %u\n", x, y);

    if (node == find) {
        printf("found node at %u, %u\n", x, y);
        coordinate_t coords;
        coords.x = x;
        coords.y = y;
        return coords;
    }

    for (uint16_t i = 0; i < node->child_count; i++) {
        node_pos_(x + i, y + 1, node->children[i], find);
    }
}

coordinate_t node_pos(node_t *root, node_t *node) { 
    return node_pos_(0, 0, root, node);
}

int main() {
    coordinate_t coords = node_pos(root, child2);

    printf("coordinates of %s: %u, %u\n", child2->name, coords.x, coords.y);

    return 0;
}

输出:

0, 0
0, 1
0, 2
1, 2
1, 1
found node at 1, 1
coordinates of child2: 2, 0

最佳答案

目前,您的 node_pos_函数不会在所有执行路径中返回一个值,并且无法向调用者指示是否找到该节点。对于在树中搜索节点的递归算法,这两者都是必不可少的。

本着归一的精神coordinate_t按值,我保留了坐标对( UINT16_MAXUINT16_MAX )来表示“未找到”的情况。

修改后的函数如下:

coordinate_t node_pos_(uint16_t x, uint16_t y, node_t *node, node_t *find) {
    coordinate_t coords;

    printf("%u, %u\n", x, y);

    if (node == find) {
        printf("found node at %u, %u\n", x, y);
        coords.x = x;
        coords.y = y;
        return coords;
    }

    // look for node in children
    for (uint16_t i = 0; i < node->child_count; i++) {
        coords = node_pos_(x + i, y + 1, node->children[i], find);
        if (!(coords.x == UINT16_MAX && coords.y == UINT16_MAX)) {
            // found
            return coords;
        }
    }

    // not found
    coords.x = UINT16_MAX;
    coords.y = UINT16_MAX;
    return coords;
}

正如@yano 所指出的,%u 的使用打印 uint16_t 的 printf 格式说明符值(value)不可移植。一个简单的解决方法是将值转换为 unsigned int如下:

        printf("found node at %u, %u\n", (unsigned)x, (unsigned)y);

避免类型转换的“正确”修复方法是使用 #include <inttypes.h> 中的 printf 格式说明符宏如下:

        printf("found node at %" PRIu16 " , %" PRIu16 "\n", x, y);

关于c - 按值返回结构每次都会给出相同的错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647508/

相关文章:

在 C 中将多个字节转换为文件大小

带空格的字符数组输入

C - fopen() 不起作用(返回空指针)

c - 删除二叉搜索树中的最低值

c - cudaMemcpy2D 的段错误

c - libpng 1.5.10 错误 : dereferencing pointer to incomplete type

c - for 循环中 rand() 的逻辑困惑

c - 如何从目标文件中读取 Mach-O 头文件?

c - memset 导致数组下溢,如何检测

c++ - C/C++ 中的高效变量监视