-1

I have this code:

typedef struct node* AVLNode;

struct node
{
    char Word[50];
    AVLNode Left;
    AVLNode Right;
};

void Insert(char* S, AVLNode T)
{
    if( T == NULL )
    {
        T = malloc( sizeof( struct node ) );
        if( T == NULL )
            printf( "Out of space!!!" );
        else
        {
            strcpy(T->Word, S);
            T->Left = T->Right = NULL;
        }
    }
    
}


int main(){

AVLNode tree = NULL;
Insert("SRING!!!", tree);
printf(tree->Word);

}

In Insert("SRING!!!", tree); I give it a pointer to the node (AVLNode type), it should find that it printf(tree->Word); equals null and give it a size (malloc) and copy string to T->Word, but printf(tree->Word); prints nothing, why is that and how can I solve it?

Thanks

Balawi28
  • 119
  • 7
  • 2
    T is passed by value, so assigning it with anything in the function does not modify `tree`, which remains `NULL`. You are (un)lucky to not get segfault when printing. – Eugene Sh. Dec 14 '20 at 20:50
  • C11 draft standard n1570: *6.5.2.2 Function calls 4 An argument may be an expression of any complete object type. In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument. 93)A function may change the values of its parameters, but these changes cannot affect the values of the arguments[...]* – EOF Dec 14 '20 at 20:52
  • A general remark - hiding a pointer behind a typedef is considered a bad practice. – Eugene Sh. Dec 14 '20 at 21:06
  • Thank you guys, can I ask why hiding a pointer behind a typedef is considered bad practice? – Balawi28 Dec 15 '20 at 12:19

1 Answers1

1

Parameter T is a local variable. You need to pass reference to pointer (pointer to pointer).

void Insert(char* S, AVLNode *T)
{
    if( *T == NULL )
    {
        *T = malloc( sizeof( struct node ) );
        if( *T == NULL )
            printf( "Out of space!!!" );
        else
        {
            strcpy((*T)->Word, S);
            (*T)->Left = (*T)->Right = NULL;
        }
    }
    
}


int main()
{
    AVLNode tree = NULL;
    Insert("SRING!!!", &tree);
    printf(tree->Word);
}
0___________
  • 60,014
  • 4
  • 34
  • 74