0
0
CHow-ToBeginner · 3 min read

How to Access Structure Members in C: Syntax and Examples

In C, you access structure members using the . operator when you have a structure variable, and the -> operator when you have a pointer to a structure. These operators let you read or modify the values inside the structure.
📐

Syntax

To access members of a structure in C, use the following syntax:

  • Dot operator (.): Used when you have a structure variable.
  • Arrow operator (->): Used when you have a pointer to a structure.

Example syntax:

structure_variable.member_name;  // Access member using dot operator
pointer_to_structure->member_name;  // Access member using arrow operator
c
struct Person {
    char name[50];
    int age;
};

struct Person p1;
p1.age = 30;  // Using dot operator

struct Person *p2 = &p1;
p2->age = 35;  // Using arrow operator
💻

Example

This example shows how to define a structure, create a variable and a pointer to it, and access members using both . and -> operators.

c
#include <stdio.h>

struct Person {
    char name[50];
    int age;
};

int main() {
    struct Person p1 = {"Alice", 28};
    struct Person *pPtr = &p1;

    // Access using dot operator
    printf("Name: %s, Age: %d\n", p1.name, p1.age);

    // Access using arrow operator
    pPtr->age = 29;  // Change age through pointer
    printf("Updated Age: %d\n", pPtr->age);

    return 0;
}
Output
Name: Alice, Age: 28 Updated Age: 29
⚠️

Common Pitfalls

Common mistakes when accessing structure members include:

  • Using the dot operator on a pointer instead of the arrow operator.
  • Using the arrow operator on a structure variable instead of a pointer.
  • Forgetting to initialize pointers before accessing members.

Wrong and right usage example:

c
#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point pt = {10, 20};
    struct Point *ptr = &pt;

    // Wrong: Using dot operator on pointer (will cause error)
    // printf("X: %d\n", ptr.x);  // Incorrect

    // Right: Use arrow operator on pointer
    printf("X: %d\n", ptr->x);  // Correct

    // Wrong: Using arrow operator on variable (will cause error)
    // printf("Y: %d\n", pt->y);  // Incorrect

    // Right: Use dot operator on variable
    printf("Y: %d\n", pt.y);  // Correct

    return 0;
}
Output
X: 10 Y: 20
📊

Quick Reference

OperatorUsageExample
.Access member of a structure variablep1.age
->Access member through a pointer to structurepPtr->age

Key Takeaways

Use the dot operator (.) to access members of a structure variable.
Use the arrow operator (->) to access members through a pointer to a structure.
Never mix dot and arrow operators incorrectly; they cause compile errors.
Always initialize pointers before accessing structure members through them.
Accessing structure members lets you read or change the data inside the structure.