【发布时间】:2019-10-31 16:21:01
【问题描述】:
我正在尝试按值返回结构以查找树中节点的位置。但是使用包装器来简化函数调用会返回不正确的值。
相关代码:
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
【问题讨论】:
-
请发送minimal reproducible example。显示的代码看起来不可编译。
-
在
node_pos_中,如果node == find不正确,则不会返回任何内容。 -
如果
node != find那你返回什么?我认为您需要重新考虑递归函数的实现。 -
您应该会收到来自编译器的警告。请务必为 gcc 启用警告
-Wall,为 Microsoft 启用警告/W3。然后阅读并修复所有的警告。 -
你打算如何表示“未找到”的结果?
标签: c