passing structure to function in c language

Advertisements

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.

>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.

Leave a ReplyCancel reply