Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Structure Functions in C

Introduction

Structures in C are used to group different types of variables under a single name. This is particularly useful for handling related data. When working with structures, it's common to perform operations on them using functions. This tutorial will guide you through the process of defining and using functions with structures in C.

Defining a Structure

Before we dive into functions, let's define a simple structure. Consider a structure to store information about a student:

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

Passing Structures to Functions

Structures can be passed to functions in two ways: by value or by reference.

Passing by Value

When a structure is passed by value, a copy of the structure is created. Changes made to the structure inside the function do not affect the original structure.

#include <stdio.h>

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

void displayStudent(struct Student s) {
    printf("Name: %s\n", s.name);
    printf("Age: %d\n", s.age);
    printf("GPA: %.2f\n", s.gpa);
}

int main() {
    struct Student student1 = {"John Doe", 20, 3.5};
    displayStudent(student1);
    return 0;
}
Name: John Doe
Age: 20
GPA: 3.50

Passing by Reference

When a structure is passed by reference, a pointer to the structure is passed. Changes made to the structure inside the function will affect the original structure.

#include <stdio.h>

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

void modifyStudent(struct Student *s) {
    s->age = 21;
    s->gpa = 3.8;
}

int main() {
    struct Student student1 = {"John Doe", 20, 3.5};
    modifyStudent(&student1);
    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("GPA: %.2f\n", student1.gpa);
    return 0;
}
Name: John Doe
Age: 21
GPA: 3.80

Returning Structures from Functions

Functions can also return structures. This is useful when creating a new structure or modifying an existing one and returning the updated structure.

#include <stdio.h>

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

struct Student createStudent(char name[], int age, float gpa) {
    struct Student s;
    strcpy(s.name, name);
    s.age = age;
    s.gpa = gpa;
    return s;
}

int main() {
    struct Student student1 = createStudent("Jane Doe", 22, 3.9);
    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("GPA: %.2f\n", student1.gpa);
    return 0;
}
Name: Jane Doe
Age: 22
GPA: 3.90

Conclusion

In this tutorial, we explored how to define structures in C and use them with functions. We covered passing structures to functions by value and by reference, as well as returning structures from functions. Understanding these concepts is crucial for effectively managing and manipulating structured data in your C programs.