3.4 Difference between passing structure by value and by pointer

By Value :



#include<stdio.h>

struct node

{
        int date;
        int num;
        char name;
};
void fun(struct node n);

main()
{
        struct node n;
        fun(n);
}
void fun(struct node n1)
{
        n1.date = 10;
        n1.num  = 99;
        n1.name = 'a';
        printf("%d %d %c\n",n1.date,n1.num,n1.name);
        printf("size of node = %d\n",sizeof(struct node));

}

op:

10 99 a
size of node = 12
Note : passing a structure it takes 12 bytes
 ------------------------------------------------------------------------------------------------------------------------------------
 By Pointer :


#include<stdio.h>

struct node

{

        int date;

        int num;

        char name;

};

void fun(struct node *n);



main()

{

        struct node n;

        fun(&n);

}

void fun(struct node *n1)

{

        n1->date = 10;

        n1->num  = 99;

        n1->name = 'a';

        printf("%d %d %c\n",n1->date,n1->num,n1->name);

        printf("size of node = %d\n",sizeof(n1));



}


Op :

10 99 a

size of node = 4


Note : passing a pointer it takes only 4 bytes.

------------------------------------------------------------------------------------------------------------------------------------ 

Differences :

1 Structure passing through a pointer faster than passing through a value.

2 Structure passing through a pointer we saves the memory. Because structure passing through a pointer it takes only 4 bytes in above program.The same program strucutre passing through a value it takes 12 bytes.
    

Author

Written by Admin

Aliquam molestie ligula vitae nunc lobortis dictum varius tellus porttitor. Suspendisse vehicula diam a ligula malesuada a pellentesque turpis facilisis. Vestibulum a urna elit. Nulla bibendum dolor suscipit tortor euismod eu laoreet odio facilisis.

0 comments: