Accessing structure members

Lesson 6.2: Accessing Structure Members


In the previous lesson, you learned how to define structures. Now, let's explore how to work with the individual components (members) within a structure.


Accessing Members with the Dot Operator (.)


The dot operator (.) is used to access the members of a structure variable.

You place the structure variable name before the dot, followed by the member name you want to access.

C

struct Student {

    char name[50];

    int age;

    float gpa;

};


int main() {

    struct Student student1 = {"Alice Johnson", 20, 3.8};

    

    printf("Name: %s\n", student1.name);     // Access the name member

    printf("Age: %d\n", student1.age);       // Access the age member

    printf("GPA: %.2f\n", student1.gpa);    // Access the gpa member


    // Modify a member's value

    student1.age = 21; 

    printf("Updated age: %d\n", student1.age); // Output: Updated age: 21


    return 0;

}

Accessing Members with Pointers to Structures


If you have a pointer to a structure variable, you can use the arrow operator (->) to access its members.

The arrow operator combines dereferencing the pointer and accessing the member in a single operation.

C

struct Student student2 = {"Bob Smith", 22, 3.6};

struct Student *ptr = &student2; // Pointer to student2


printf("Name: %s\n", ptr->name);  // Access the name member using the arrow operator


Nested Structures


You can nest structures within other structures, creating hierarchical data organizations.

C

struct Date {

    int day;

    int month;

    int year;

};


struct Employee {

    char name[50];

    struct Date birthDate;

    double salary;

};


int main() {

    struct Employee employee1 = {"John Doe", {15, 8, 1990}, 55000.00};


    printf("Birthdate: %d/%d/%d\n", employee1.birthDate.day, employee1.birthDate.month, employee1.birthDate.year);


    return 0;

}

Passing Structures to Functions


You can pass entire structure variables to functions, either by value or by reference (using pointers).

C

void printStudentInfo(struct Student s) {

    printf("Name: %s, Age: %d, GPA: %.2f\n", s.name, s.age, s.gpa);

}


// ... 

printStudentInfo(student1); 


Key Points


Dot Operator (.): Used to access members of a structure variable.

Arrow Operator (->): Used to access members of a structure through a pointer.

Nested Structures: Organize data hierarchically within structures.

Passing Structures to Functions: Pass entire structures to functions for processing.

Let me know if you'd like any clarification or want to see more examples of accessing structure members.

Course Syllabus