我刚开始编码并有一个初学者的问题。所以我有一棵二叉树。在我添加第一个节点后,我想搜索树,看看是否有任何具有相同值的重复节点。但是当我尝试搜索只有一个节点的树时,我一直收到错误: 这是我的节点:
<?php
$postsPerPageq = 5;
$allargw = array(
'post_type' => 'audioplayer',
'posts_per_page' => $postsPerPageq,
'orderby' => 'title',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'audiotop',
'field' => 'slug',
'terms' => 'top-audio'
)
)
);
$topaudio = new WP_Query($allargw);
while ( $topaudio->have_posts() ) : $topaudio->the_post();
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
<?php endwhile; wp_reset_postdata();?>
这是我用来创建第一个节点的函数
struct node{
int data;
struct node* left;
struct node* right;};
我这样添加了它:
struct node* createnode(int num){
struct node *p=malloc(sizeof(struct node*));
p->data=num;
return p;
}
这是搜索功能
struct node *root;
root=createnode(b);
这是我得到的错误
char * search(int num, struct node *p, int dep){
dep=1;
char *result="n";
if(p==NULL){result="n";return result;}
struct node * root;
root=p;
while(root!=NULL){
if(num==root->data){
result= "y";break;
}
if(num>root->data && root->right!=NULL){
root=root->right;dep++;
}
if(num<root->data&&root->left!=NULL){
root=root->left;dep++;
}
if(num >root->data&&root->right==NULL){
result= "n";break;
}
if(num <root->data&&root->left==NULL){
result="n";break;
}
}
return result;
}
感谢所有愿意帮助的人!!!!
答案 0 :(得分:3)
struct node *p = malloc(sizeof(struct node*));
您需要为struct本身分配足够的内存,而不是指向struct的指针。
struct node *p = malloc(sizeof(struct node));
如果您取消引用目标指针并将其大小作为参数传递给malloc
,则更容易记住这样做:
struct node *p = malloc(sizeof(*p));
如果要在程序的更高版本中更改p的数据类型,则不需要将相应的参数更新为malloc
。
答案 1 :(得分:0)
一个典型的错误是分配内存不是为了结构的大小,而是为了指向它的指针。 Synchronizer在他的回答中显示了solution问题:
struct node *p = malloc(sizeof(struct node));
我还应该补充一点,malloc可以返回一个潜在的空指针(link),这就是为什么在分配内存之后应该在取消引用之前检查null:
struct node* createnode(int num)
{
struct node *p = malloc(sizeof(struct node));
if (p != NULL) // <=
{
p->data = num;
}
return p;
}
很遗憾找到错误需要花费很多时间。也许,使用静态分析器可以帮助更早地发现错误。 Here你可以看到在大项目中如何犯下类似的错误。