【问题标题】:Use of ** in BST insert( )在 BST insert( ) 中使用 **
【发布时间】:2017-04-26 08:02:57
【问题描述】:

以下是我的 BST 插入函数代码。有人能解释一下为什么会出现分段错误吗?

#include <stdio.h>
#include <stdlib.h>

struct node{
    int value;
    struct node* right;
    struct node* left;
};

struct node* insert(struct node* n,int age){
    if (n==NULL){
        n = malloc(sizeof(struct node));   
        n->value = age;
        n->left = n->right = NULL; 
    }
    else if(age < n->value){ 
        n->left = insert(n->left, age);
    }
    else {
        n->right = insert(n->right, age);
    }
    return n;
}

void main(){
    int age;
    struct node* n=NULL;
    scanf("%d",&age);
    while (age!=-1){
        n=insert(n,age);    
        scanf("%d",&age);
    }
}

我提到了this,它建议使用**(引用指针)。

f( &px );
//...

void f( int **px )
{
    *px = malloc( sizeof( int ) );

    printf( "*px = %p\n", *px );
}

但是为什么我们不能通过将返回类型从void 更改为node* 来避免使用**?

【问题讨论】:

  • insert 总是崩溃。你的编译器不会对此发出警告吗?
  • main 应该返回 int,而不是 void
  • 您缺少#include &lt;stdlib.h&gt;#include &lt;stdio.h&gt;
  • if (n=NULL){ --> if (n==NULL){ 需要return n; end of insert
  • @AlekhyaVellanki 因为n=NULLNULL 分配给n,然后下面的n-&gt;value 取消引用一个空指针。你用的是什么编译器?

标签: c pointers binary-search-tree


【解决方案1】:

这似乎对我有用。除了你使用scanf() 的方式外,我并没有对你的代码进行太多更改,当你输入1 时,它并没有结束。

最好只调用一次scanf,并确保允许连续输入,使用while (scanf(.....) == 1,以确保始终读取一个值直到终止,在这种情况下,直到age 是@987654326 @。

除非我遗漏了什么,否则这是建议的代码:

#include <stdio.h>
#include <stdlib.h>

struct node{
    int value;
    struct node* right;
    struct node* left;
};

struct node* insert(struct node* n,int age){
    if (n==NULL){
        n = malloc(sizeof(struct node));   
        n->value = age;
        n->left = n->right = NULL; 
    }
    else if(age < n->value){ 
        n->left = insert(n->left, age);
    }
    else {
        n->right = insert(n->right, age);
    }
    return n;
}

void
print_tree(struct node *n) {
    if (n != NULL) {
        print_tree(n->left);
        printf("%d\n", n->value);
        print_tree(n->right);
    }
}

int main(){
    int age;
    struct node* n = NULL;

    printf("Enter some numbers(1 to stop): ");
    while (scanf("%d", &age) == 1 && age != 1) {
        n = insert(n, age);
    }

    printf("\nYour numbers inserted into BST:\n");
    print_tree(n);

    return 0;
}

【讨论】:

  • 我刚刚将我的void main() 更改为int main(),它可以工作。谢谢!但我不明白为什么void 没有工作。
  • 这个答案似乎没有解决任何段错误。就目前而言,问题中的代码似乎是正确的。以@RoadRunner 建议的方式使用scanf 是个好主意,但不是必需的。
猜你喜欢
  • 2020-09-19
  • 1970-01-01
  • 2021-02-20
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
相关资源
最近更新 更多