Referencing Structure Members

In C programming, after defining a structure, we can reference individual members of that structure. We use the dot (.) operator to access each member within a structure variable. Here, we'll discuss how to reference structure members with examples.

Explanation

Once a structure variable is declared, each member within that structure can be accessed directly by using the dot(.) operator. This operator enables us to read and modify individual members of the structure. For example, if we have a structure representing a student, we can access each member, like name, age, or grade, using this operator.

Example:


#include <stdio.h>
// Defining a Structure for Student
struct Student {
    char name[50];
    int age;
    float grade;
};
int main() {
    // Declaring and initializing a structure variable
    struct Student student1 = {"Alice", 20, 89.5};

    // Accessing structure members using dot operator
    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("Grade: %.1f\n", student1.grade);
    return 0;
}

Output

Name: Alice Age: 20 Grade: 89.5

The dot operator can only be used when directly accessing members within a structure variable. For pointers to structures, we use the arrow (->) operator, Here’s a detailed explanation: