MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Structure as Function Argument

Using structures as function arguments allows you to pass complex data types to functions in a structured way. You can pass structures to functions either by value or by reference (using pointers). Here’s an explanation with examples in C.

Passing Structures by Value

When a structure is passed by value, a copy of the entire structure is passed to the function. This means changes made to the structure within the function do not affect the original structure.

Example

Consider the Person structure:

struct Person {
char name[50]; int age; float height; };

Here’s how you pass it by value:

#include <stdio.h>
#include <string.h> struct Person { char name[50]; int age; float height; }; void printPerson(struct Person p) { printf("Name: %s\n", p.name); printf("Age: %d\n", p.age); printf("Height: %.1f\n", p.height); } int main() { struct Person person1 = {"John Doe", 30, 5.9}; printPerson(person1); return 0; }

here, printPerson(struct Person p) is a function that takes a Person structure by value and prints its members, In main(), printPerson(person1) is called, passing person1 by value to the function, Inside printPerson, a copy of person1 is used.


Passing Structures by Reference

Passing structures by reference involves passing a pointer to the structure. This allows the function to modify the original structure.

Example

Here’s how you pass a structure by reference:

#include <stdio.h>
#include <string.h> struct Person { char name[50]; int age; float height; }; void updatePerson(struct Person *p) { p->age += 1; p->height += 0.1; } void printPerson(struct Person p) { printf("Name: %s\n", p.name); printf("Age: %d\n", p.age); printf("Height: %.1f\n", p.height); } int main() { struct Person person1 = {"John Doe", 30, 5.9}; updatePerson(&person1); // Pass by reference printPerson(person1); return 0; }


here, updatePerson(struct Person *p) is a function that takes a pointer to a Person structure,

p->age += 1; increments the age member by 1 and, 

p->height += 0.1; increments the height member by 0.1.


in main(), updatePerson(&person1) is called, passing a pointer to person1 using the & operator, printPerson(person1) is then called to print the updated person1.


Using structures as function arguments helps manage complex data more effectively and allows for cleaner, more modular code.

Report an issue

Reporting: Structure as Function Argument (topic)

Related Posts