Struct

Struct

struct: User-defined data type for combining data items with different types into one.

struct USTMember {
    char name[20];
    int ID;
    int age;
} student;
/**
 *  `USTMember` is an optional structure tag.
 *  `student` is a variable name of type `struct USTMember`.
 *  Declaring variables after the struct is optional.
 */

You can access members of the structure using the dot operator .. For example: Student.ID or Student.age.

Sample Code

#include <stdio.h>
#include <string.h>

struct USTMember {
    char name[20];
    int ID;
    int age;
};

void print_info(struct USTMember student) {
    printf("Student Name : %s\n", student.name);
    printf("Student ID : %d\n", student.ID);
    printf("Student Age : %d\n", student.age);   
}

int main() {
    struct USTMember student; /* variable `student` of type `USTMember` */
    strcpy(student.name, "John");
    student.ID = 1010;
    student.age = 18;
    
    print_info(student);
    return 0;
}

To access members of pointers to struct, use -> instead of ..

struct USTMember* student;
student->ID = 1010;
student->age = 18;

Last updated