Wednesday, 9 June 2021

Structures and functions in C

 For structures to be fully useful, we must have a mechanism to pass them to function and return them, A structure may be passed to the functions in three different ways.

  1. Passing individual members
  2. Passing entire structure
  3. Passing structure using address


 

1. Passing individual members

To pass individual members of the structure to a function we must use the dot operator to refer the individual members for the actual parameters.

Example1:

#include<stdio.h>
struct student
{
int no;
char name[30];
float fee;
};
void display(int n);
void main()
{
 struct student s={101,"hari",15,000};
 display(s.no);
 }
 void display(int n)
 {
 printf("%d",n);
 }

2. Passing entire structure 

To pass an entire structure to a function we are actually passing the structure variable from calling function to called function.

Example2:

#include<stdio.h>
#include<string.h>
struct student
{
int no;
char name[30];
float fee;
};
void display(struct student s);
void main()
{
 struct student s={101,"hari",15,000};
 display(s);
 }
 void display(struct student s))
 {
 printf("%d",s.no);
 printf("%f",s.fee);
 puts(s.name);
 }

3. Passing structure using address

In this case, the address location of the structure is passed to the calling function. The function can access indirectly the entire structure and work on it.

Example3:

#include<stdio.h>
#include<string.h>
struct student
{
int no;
char name[30];
float fee;
};
void display(struct student *s);
void main()
{
 struct student s={101,"hari",15,000};
 display(&s);
 }
 void display(struct student *s))
 {
 printf("%d",s->no);
 printf("%f",s->fee);
 puts(s->name);
 }

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top