Passing Structures as Function Arguments in C


In C, structures can be passed as arguments to functions just like any other data type. This can be done by passing the structure variable, or a pointer to the structure, as an argument to the function.

Passing structure variables as arguments: When a structure variable is passed as an argument to a function, a copy of the structure is passed to the function. This means that any changes made to the structure inside the function will not affect the original structure.

This program demonstrates how to pass a structure as an argument to a function in C.

  • A structure called "student" is defined with three members: name, age, and per. These members are defined as a pointer to a character (string), an integer, and a floating-point number, respectively.
  • In the main function, an instance of the "student" structure is created with the name "RAM", age 25, and percentage 75.5.
  • The program defines a function called "display()" which takes a single argument of the "student" structure type. Inside the function, the members of the structure are accessed and displayed using the printf() function.
  • In the main function, the structure instance is passed as an argument to the "display()" function. When the function is called, a copy of the structure is passed to the function, so any changes made to the structure inside the function will not affect the original structure.
  • In the display function the members of the structure are accessed using the dot operator(.) and the printf function is used to print the values.
  • Finally, the program ends with a return 0 statement, which indicates that the program has executed successfully.

It's important to note that in this program, the structure member name is defined as a pointer to a character, which means it's pointing to a memory location that holds the name, it's not storing the name itself. So, it's important to make sure that the memory location pointed by the pointer is valid and has been allocated before passing the structure to the display function.

Source Code

//Structure  as function arguments in C Programming
 
 
#include<stdio.h>
struct student
{
    char *name;
    int age;
    float per;
};
void display(struct student o)
{
    printf("\nName        : %s",o.name);
    printf("\nAge         : %d",o.age);
    printf("\nPercent     : %f",o.per);
}
int main()
{
    struct student o={"RAM",25,75.5};
    display(o);
 
    return 0;
}
 
To download raw file Click Here

Output

Name        : RAM
Age         : 25
Percent     : 75.500000

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C