Search code examples
cpointersstructbinary-tree

Use of ampersand (&) along with arrow operator (->) for inputting data into a struct in C, is it necessary?


My professor is currently teaching Binary Trees at college and she gave us a program to create a binary tree in C using Linked Lists.

However, there was a debate on whether ampersand (&) has to be used along with arrow operator (->) for inputting the node data into the tree's struct.

This is the snippet of the code that she gave us for creating a node:

BinTree *createNode() {
    BinTree* newnode;
    newnode = (BinTree*)malloc(sizeof(BinTree));
    printf("Enter data: ");
    scanf(" %c",newnode->data);
    newnode->lchild=NULL;
    newnode->rchild=NULL;
    return newnode;
}

However, when I run the entire finished code on my computer, the program terminates after giving the input.

1.Create
 2.Inorder
 3.preorder
 4.postorder
 5.exit
Enter your choice:1
 Enter data:A

Process finished with exit code -1073741819 (0xC0000005)

However, when I add an ampersand & to the scanf, the code executes perfectly.

BinTree *createNode() {
    BinTree* newnode;
    newnode = (BinTree*)malloc(sizeof(BinTree));
    printf("Enter data: ");
    scanf(" %c",&newnode->data);
    newnode->lchild=NULL;
    newnode->rchild=NULL;
    return newnode;
}

I get the following output where the program doesn't terminate with an error code anymore.

1.Create
 2.Inorder
 3.preorder
 4.postorder
 5.exit
Enter your choice:1
 Enter data:A
 if you want left child press 1
1
Enter data:A
 if you want left child press 1

Which kind of confirms that the ampersand was quite important in this program. However, during Linked Lists, I have never used any ampersands while inserting data into the linked list nodes.

Why did I have to use an ampersand here then if the arrow operator -> is already pointing to the a struct member?


Solution

  • The ampersand & is necessary if you use scanf, because it provides the address of the variable. The arrow operator -> accesses the value directly, not its address, so & is needed to get the address of that member.