C Structure as Function Argument

beginner
14 min

C Structure as Function Argument

Welcome to another exciting lesson on C Programming at CodeYourCraft! Today, we're diving into using Structures as Function Arguments. Let's get started! šŸŽÆ

What is a Structure?

A structure (or struct) is a user-defined data type that allows us to group related variables together in C. It's like creating a custom box where we can store multiple items.

c
struct Student { char name[50]; int age; float gpa; };

In this example, we've defined a structure named Student with three properties: name, age, and gpa.

šŸ“ Note: The keyword struct is optional when declaring variables of a custom type.

Passing Structures to Functions

Now that we have our Student structure, let's learn how to pass it as an argument to a function.

c
#include <stdio.h> struct Student { char name[50]; int age; float gpa; }; void displayStudent(struct Student student) { printf("Name: %s\n", student.name); printf("Age: %d\n", student.age); printf("GPA: %.2f\n", student.gpa); } int main() { struct Student student = {"John Doe", 20, 3.8}; displayStudent(student); return 0; }

In this example, we've defined a function called displayStudent that takes a Student structure as an argument and prints its details. In the main function, we create a Student object with some sample data and call the displayStudent function with it as an argument.

Passing Structures by Reference

There's another way to pass structures as function arguments: by reference. This approach allows the function to modify the original structure passed to it.

c
#include <stdio.h> void incrementAge(struct Student *student) { student->age++; } struct Student { char name[50]; int age; float gpa; }; int main() { struct Student student = {"John Doe", 19, 3.8}; printf("Before increment: Age = %d\n", student.age); incrementAge(&student); printf("After increment: Age = %d\n", student.age); return 0; }

Here, we've created a function called incrementAge that takes a pointer to a Student structure. By passing the address of the student object (&student), the function can increase the age of the student by one.

Quick Quiz
Question 1 of 1

What's the advantage of passing structures by reference?

That's it for today! In the next lesson, we'll explore more advanced topics related to C structures. Stay tuned and keep coding! šŸ’”

Happy learning! šŸ“