0

I am in week 5(data structures) and I tried to make a simple binary search tree. then I tried to create a function for getting around on this tree! this is a part of get_around function :

    printf("tree->number = %i\ntree->right = %p\ntree->left = %p\n" , tree->number ,tree- 
    >right,tree->left) ;
    printf("In which way do yo want to continue(right = r , left = l ,end = any character) ?\n") ;

    printf("&tree->right1= %p\n",&tree->right) ;
    char way ;
    scanf("%s" , &way) ;
    printf("&tree->right2=%p\n",&tree->right) ;

    if(way == 'r' && tree->right != NULL)
    {
        get_around(tree->right) ;
    } 

there are two "printf" before and after "scanf" and they should print the same thing , but they print different addresses ! when I omit scanf , address doesn't change at all and function works !!! Why my allocated memory (tree->right) should change after "scanf" ?

1
  • Your code is different in the two printf statements above. The first says printf("&tree->right1 and the second says printf("&tree->right2. Is that how it is in your actual code? Because right now, you appear to be referencing two different things. Jan 13 at 23:31
0

You are printing tree->right the first time and &tree->right) the second time. So those won't be the same, since the first is the address stored in your variable tree->right and the second is the address of your variable tree->right

char way ;
scanf("%s" , &way) ;

You are scanning for a string (%s) but only have space in memory for a char. The memory after the 1 char will be overwritten with the rest of the string (whatever was entered at the terminal, including a null char to end the string). That may be overwriting the tree->right variable?

4
  • Hi and thanks . but if you notice, there are two "printf" before and after "scanf" , and both of them are same !! (&tree->right)
    – logan
    Jan 13 at 18:21
  • see my edit above
    – curiouskiwi
    Jan 13 at 23:18
  • I need only one character , it's not the problem !
    – logan
    Jan 28 at 12:17
  • if you only need one character then you should use "%c" not %s
    – curiouskiwi
    Jan 28 at 20:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .