0
0
C++programming~5 mins

Accessing structure members in C++

Choose your learning style9 modes available
Introduction

Structures group related data together. Accessing members lets you use or change each piece inside the group.

You want to store information about a person, like name and age, in one place.
You need to keep details of a book, such as title and author, together.
You are working with a point in 2D space and want to access its x and y coordinates.
You want to organize data about a car, like model and year, in a single variable.
Syntax
C++
struct StructureName {
    dataType member1;
    dataType member2;
    // more members
};

StructureName variableName;
variableName.member1 = value;
value = variableName.member2;

Use the dot . operator to access members of a structure variable.

Each member can be accessed or changed individually.

Examples
Defines a Person structure and sets age and height using dot operator.
C++
struct Person {
    int age;
    float height;
};

Person p;
p.age = 25;
p.height = 5.9f;
Creates a Point with x=10 and y=20, then reads x value.
C++
struct Point {
    int x;
    int y;
};

Point pt = {10, 20};
int xValue = pt.x;
Sample Program

This program creates a Car structure, assigns values to its members, and prints them.

C++
#include <iostream>
#include <string>
using namespace std;

struct Car {
    string model;
    int year;
};

int main() {
    Car myCar;
    myCar.model = "Toyota";
    myCar.year = 2020;

    cout << "Car model: " << myCar.model << "\n";
    cout << "Car year: " << myCar.year << "\n";
    return 0;
}
OutputSuccess
Important Notes

Remember to include #include <iostream> and use std::cout or using namespace std; for printing.

Structure members are accessed with the dot operator only when you have a structure variable, not a pointer.

Summary

Structures group related data under one name.

Use the dot operator . to access or change members.

Each member can be used like a normal variable.