微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我在函数 ins() 中放入 r=NULL 时,程序没有发生任何影响

如何解决当我在函数 ins() 中放入 r=NULL 时,程序没有发生任何影响

在处理指针时,我们正在处理地址,对吗?

所以当一个 struct node pointer n 被传递给 t(struct node *t=n) 并且稍后如果 t 被分配了 NULL 不应该 n 也变成 NULL 吗?

ps-:这是一个二叉树的程序

#include<stdio.h>   //check at third line of ins() function
#include<stdlib.h>
struct node{
int data;
struct node* left,*right;
};
struct node* n(int dat){
struct node *x=(struct node*)malloc(sizeof(struct node));
x->data=dat;
x->left=NULL;   x->right=NULL;
return x;
};

void ins(struct node* n,struct node* r){
    struct node* t=r,*y=NULL; //ok so when i put r=NULL in this next line should this block of memory go 
    //r=NULL;                  //NULL
    while(t!=NULL){
        y=t;
        if(t->data>n->data)
        {
            if(t->left==NULL)
                {t->left=n;
                    t=NULL;
                }
            else
            t=t->left;
        }
        else {
            if(t->right==NULL){
                t->right=n;
                t=NULL;
            }else
            t=t->right;
        }
    }

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

void main(){
    struct node *a,*b,*c,*d,*e,*f,*g,*h;
    a=n(32);    b=n(20);    c=n(100);   d=n(16);
    e=n(25);    f=n(50);    g=n(144);   h=n(19);
    a->left=b;  a->right=c;
    b->left=d;  b->right=e;
    c->left=f;  c->right=g;
    ins(h,a);
    inorder(a);
}```

解决方法

使用 struct node* t=r,您正在创建一个新的独立变量 t,它指向r 相同的位置(我们称之为 A)。>

这意味着对 *r 的任何更改都会反映在 *t 中,因为它们都指向到同一个位置 A。

当将 NULL 赋值给 r 时,t 变量仍然指向位置 A,但 r 不再指向。

一个小例子:

int A = 0;
int *r = &A;
int *t = r;
// *r==0,*t==0,point to same location
*r = 55;
// *r==55,*t==55 (same location)
r = NULL;
// *t==55 (*r is no longer valid as r is NULL)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。