C: 如何在一个函数中return一个tree_node?

C: how to return a tree_node in a function?

我正在构建目录树。

我正在尝试复制 shell 'cd' 命令进入目录。

我如何return tree_node cwd 在将 cwd 设为子目录后?

(cwd = 当前工作目录, subDir = 子目录) 例如:

cwd = subDir->tree;

return顺时针; (我如何 return cwd 而不会出现错误?)

// *checks whether cwd has a subdirectory named arg
// *if yes, the function returns the corresponding tree node (and become new working directory)
// *if no, prints an error message
// *handle cd and cd ..
struct tree_node *do_cd(struct tree_node *cwd, struct tree_node *root, char *arg) {

    // checks if directory exists
    struct list_node *subDir = cwd -> first_child;

    while (subDir != NULL) {
        if (strcmp(subDir->tree->string_buffer, arg) == 0) {
            printf("Entering directory with name %s \n", arg);
            subDir->tree = cwd;
            return cwd;
            printf("Directory with name %sentered.\n", arg);
        }
        subDir = subDir->next;
    }
    printf("Directory does not exist!\n");
}

您需要 return NULL 或任何指向有效树的指针。您可以查看此代码:

struct tree_node *do_cd(struct tree_node *cwd, struct tree_node *root, char *arg) {
// checks if directory exists
struct list_node *subDir = cwd -> first_child;

while (subDir != NULL) {
    if (strcmp(subDir->tree->string_buffer, arg) == 0) {
        printf("Entering directory with name %s \n", arg);
        subDir->tree = cwd;
        printf("Directory with name %sentered.\n", arg);
        return cwd;
    }
    subDir = subDir->next;
}
printf("Directory does not exist!\n");
return NULL;
}