C:如何在函数中返回树节点?

C:如何在函数中返回树节点?,c,linked-list,treenode,C,Linked List,Treenode,我正在建立一个目录树 我正在尝试复制shell'cd'命令以进入目录 在将cwd设置为其子目录后,如何返回树\节点cwd (cwd=当前工作目录,SubDR=子目录)例如: cwd=子目录->树 返回cwd;(如何返回cwd而不出错?) 您需要返回NULL或任何指向有效树的指针。您可以检查以下代码: struct tree_node *do_cd(struct tree_node *cwd, struct tree_node *root, char *arg) { // checks if di

我正在建立一个目录树

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

在将cwd设置为其子目录后,如何返回树\节点cwd

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

cwd=子目录->树

返回cwd;(如何返回cwd而不出错?)


您需要返回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;
}

你说如果(…)然后返回cwd,那么其他条件呢?编译器给出错误,因为并非所有路径都返回“我如何返回cwd而不出错”是什么意思?你是说构建错误吗?什么构建错误?运行时错误?什么,在哪里?如果您无法更改目录,为什么不返回
NULL
?您必须在函数的所有路径中返回某些内容,否则在使用返回的指针时将抛出未定义的行为。另外,您知道
return
使函数立即返回,之后不会执行任何语句。我应该在哪里返回NULL?printf之后(“目录不存在!\n”);?在
printf之后(“目录不存在!\n”)你的第二天?那我就说你太深了!从简单的开始,一步一个脚印,然后一步一步地往上走。我建议您查看并找到一本好的入门书或教程。@JohnHascall:在函数参数中,它被定义为struct tree\u node*
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;
}