Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

passing structure to function in c language

can anyone help? why ‘&’ is not required while calling a function in this program? but is thought that ‘&’ is required in call by reference.

#include <stdio.h>
#include <stdlib.h>


struct node{
int data;
struct node *next;
};


void traversal(struct node *ptr)
{
while(ptr!=NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}
}


int main()
{
struct node *head;
struct node *second;
struct node *third;

head = (struct node*) malloc(sizeof(struct node));
second = (struct node*) malloc(sizeof(struct node));
third = (struct node*) malloc(sizeof(struct node));

head->data = 7;
head->next = second;

second->data = 5;
second->next = third;

third->data = 12;
third->next = NULL;

traversal(head);

return 0;
}

can anyone help? why ‘&’ is not required while calling a function in this program? but is thought that ‘&’ is required in call by reference.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have a singly linked list where nodes are linked by pointers.

The function traversal does not accept an object of the type struct node. It accepts a pointer to an object of the type struct node *.

void traversal(struct node *ptr)
{
while(ptr!=NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}
}

As the original pointer used as an argument expression is not changed within the function then there is no any sense to pass it to the function by reference through a pointer to it.

Dereferencing pointers within the function as for example

ptr->data

the function has a direct access to data members of nodes pointed to by pointers.

That is is the object of the type struct node that is indeed is passed by reference to the function through a pointer to it. But еhe pointer itself is passed by value.

To make it clear consider the following simple demonstration program.

#include <stdio.h>

void f( int *px )
{
    printf( "x = %d\n", *px );
}

int main( void )
{
    int x = 10;

    int *px = &x;

    f( px );
}

As you can see to output the value of the variable x declared in main within the function f using the pointer px to x there is no need to pass the pointer itself by reference through a pointer to it. However the object x is passed to the function by reference indirectly through the pointer px.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading