0

basically I am trying to pass the pointer where address of new block needs to be stored

   void buildseg(class node *p,int a[],int l,int r)
{

    class node *temp;
    temp=createnode();
    int sum=0;
    for(int i=l;i<=r;i++)
    {
        sum=sum + a[i];
    }
    temp->val=sum;
    temp->leftrange=l;
    temp->rightrange=r;
    if(root==NULL)
    {
        root=temp;
    }
    if(l!=r)
    {
        int q=(l + r)/2;
        buildseg(temp->left,a,l,q);
        buildseg(temp->right,a,q+1,r);
    }
    else{
        temp->left=NULL;
        temp->right=NULL;
    }

    p=temp;

}

    class node{

public:
    int val;
    int leftrange;
    int rightrange;
    class node *left;
    class node *right;


};
class node *root=NULL;

class node *createnode()
{
    class node *p;
    p=(class node*)malloc(sizeof(class node));
    
    return p;


}

can anyone help me where the error lies. Whether we can pass a pointer where we have to store address of a block created by malloc function. or it's wrong over there.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Not really related to your problem, but in C++ one should almost *never* use `malloc` in C++. If you need pointers try to use a smart pointer like [`std::unique_ptr`](https://en.cppreference.com/w/cpp/memory/unique_ptr), or worst case with plain non-owning pointers use `new`. – Some programmer dude Mar 19 '21 at 09:31
  • Also, it seems that you might need to refresh your knowledge of C++ a bit more, or actually learn it properly as its own language (instead of as "C with classes"), so I suggest you get [some good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to read and learn from. – Some programmer dude Mar 19 '21 at 09:32
  • yes thank you for your wonderful suggestion, i really appreciate your concern so please can you elaborate a bit more what you actually meant by knowing c++ better?? because I know concept of STL in c++ and opps concept like inheritance, public, private and protected. what else is their in c++ which I am not aware of?? it's really a genuine request if you could list those things for me. I am still in 2nd year of engineering so i have a bit time to work on these things. so please do suggest. thank you in advance. –  Mar 19 '21 at 17:27

1 Answers1

0

Your function prototype void buildseg(class node *p,int a[],int l,int r) makes it impossible that the function changes the first parameter from the caller.

When you call it like that:

class node *x = NULL;
void buildseg(x,a, 4, 5);

The line p=temp; only changes the copy p in the function, but not x at the caller.

You have to pass the first parameter as reference:

void buildseg(class node * &p,int a[],int l,int r)
mch
  • 9,424
  • 2
  • 28
  • 42
  • how can I forget pass by value and pass by reference... thanks a lot... –  Mar 19 '21 at 09:44