C program to pass a structure to a user define function

In this C program, we are going to learn how to pass a structure type of data type to a user define function? Here, we are an example, where we are passing a structure to a function in C.
Submitted by IncludeHelp, on March 22, 2018

Given a structure and we have to pass it to a function in C.

structure declaration is:

struct exam
{
    	int marks;
    	char name[20];
};

Here,

  • exam is the structure name
  • marks and name are the members of the structure/variable of the structure

Here is the function that we are using in the program,

void structfun(struct exam obj1);

Here,

  • void is the returns type of the function i.e. function will not return any value.
  • structfun is the name of the function.
  • struct exam obj1 is the object of exam structure - while declaring a function we must have to use struct keyword with the structure name.

Structure object/variable declaration is:

    struct exam obj;

Assigning values to the structure variable inside the main

    obj.marks = 50;
    strcpy(obj.name , "Arjun kapoor");

Function calling statement,

structfun(obj);

Here, obj is the structure variable.

Program to pass a structure to a function in C

/*  
C program to a structure to a function
*/

#include <stdio.h>

// Declare a global structure since we need to pass 
// it to a function 
struct exam
{
    	int marks;
    	char name[20];
};

// define the structure by declaring the global object
struct exam obj;

 // declaration of the function
void structfun(struct exam obj1);

// function to print structure elements
void structfun(struct exam obj1)
{
    printf("\nThe name of the student is : %s",obj1.name);
    printf("\nThe marks of the student is : %d",obj1.marks);
}

// main function
int main()
{
    obj.marks = 50;
    strcpy(obj.name , "Arjun kapoor");
	
    // Passing structure to Function
    structfun(obj);
	
    return 0;
}

Output

The name of the student is : Arjun kapoor
The marks of the student is : 50

C User-defined Functions Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.