Go Back

Passing structure to functions in c programming with example c tutorial

11/18/2023
All Articles

#Passing structure functions in c programming with example c tutorial

Passing structure to functions in c programming with example c tutorial

Passing structure to functions in c programming with example

There are two common ways to pass structures to functions: passing by value and passing by reference. We have example of printStudent function takes a value of student to a struct structure and modifies its value.

Below is example of pass by value in c language:

 

#include <stdio.h>
#include <string.h>
// Outer structure
struct Date {
    int day;
    int month;
    int year;
};

// Inner structure nested inside the Date structure
struct Student {
    char name[50];
    int age;
    struct Date birthdate; // Nested structure
};
void printStudent(struct Student p) {
    printf("Name of student: %s\n", p.name);
    printf("Age: %d\n", p.age);
    printf("Birthdate: %d/%d/%d\n", p.birthdate.day, p.birthdate.month, p.birthdate.year);
}



int main() {
    // Declare a variable of the outer structure type
    struct Student person1;
    
    strcpy(person1.name, "developer Indian");
    person1.age = 25;
    // Assign values to the members of the nested structure
    person1.birthdate.day = 15;
    person1.birthdate.month = 7;
    person1.birthdate.year = 1998;

    // Access and print the values
    printStudent(person1);

    return 0;
}

 

Conclusion

When you pass a structure by value, a copy of the entire structure is passed to the function. Changes made to the structure inside the function do not affect the original structure.
You can select between passing by reference and passing by value depending on whether you need the function to work with a copy or to change the original structure.

Article