【问题标题】:Having a hard time figuring out how pointers to structs works in binary trees很难弄清楚指向结构的指针在二叉树中是如何工作的
【发布时间】:2013-03-08 06:10:05
【问题描述】:
#include<stdio.h>
#include<stdlib.h>

typedef struct              //create a pointer structure
{
int data;
struct node *left;
struct node *right;
} node;

node *insert(node *root, int x);

//Insert Function
node *insert(node *root, int x)    //Line 53        
{    
    if(!root)
    {
        root = new_node(x);
        return root;
    }

    if (root->data > x)
    {
        root->left = insert(root->left, x);   //Line 63
    }

    else 
    {
        root->right = insert(root->right, x);  // Line 68
    }

    return root;
}

编译时出现以下错误:

:在函数“插入”中:

:63:3: 警告:从不兼容的指针类型传递“插入”的参数 1 [默认启用]

:53:7: 注意:预期为“struct node *”,但参数类型为“struct node *”

:63:14: 警告:来自不兼容指针类型的赋值[默认启用]

:68:3: 警告:从不兼容的指针类型传递“插入”的参数 1 [默认启用]

:53:7: 注意:预期为“struct node *”,但参数类型为“struct node *”

:68:15: 警告:来自不兼容指针类型的赋值[默认启用]

  1. 为什么我的插入函数中的第一个参数与我传递给它的参数不兼容?
  2. 如何将指针分配给“结构指针”?

【问题讨论】:

    标签: pointers struct binary-search-tree


    【解决方案1】:

    将结构体定义改为

    struct node             //create a pointer structure
    {
        int data;
        struct node *left;
        struct node *right;
    };
    

    以及函数原型

    struct node *insert(struct node *root, int x);
    

    【讨论】:

    • 两种声明方式有什么区别?
    • 一个长话题struct vs typedef
    • 这帮了很多忙!我不认为“速记”定义适合我。指针和 BST 的概念仍然有些模糊。有没有可以推荐的文章对您有帮助?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2019-03-12
    • 2016-05-01
    • 1970-01-01
    • 2023-03-20
    • 2021-07-22
    相关资源
    最近更新 更多