The answer: the dot operator (.)
The operator that connects a structure variable to its members is the dot (.). Write the variable’s name, a dot, and the member’s name:
#include <iostream>
struct Car {
int year;
double price;
};
int main() {
Car car{}; // year and price start at 0
car.year = 2024; // the dot reaches the member year
car.price = 18500.0; // and the member price
std::cout << car.year << "\n"; // prints 2024
}
In C and C++, a structure is written as a struct, so “structure variable” here means a variable of a struct type. In C, you declare it with the keyword, as in struct Car car;, but the dot is used in the same way.
A pointer to a structure uses ->
If you have a pointer to a structure rather than the structure itself, the dot does not work directly on the pointer. Use the arrow (->), which reaches the member through the pointer:
Car* ptr = &car;
ptr->year = 2025; // arrow: change the member through the pointer
(*ptr).price = 19000.0; // same idea: dereference first, then use the dot
Both forms change members of the same car. The two are equivalent, and the arrow is shorter, which is why most code uses it.
“Elements” here means members
The question says “elements”, but in this context it means members: the named parts of a structure. Array elements are a different thing and are picked with brackets. In an array of structs, cars[0] is one element, and cars[0].year uses the dot to pick the member year from that element:
Car cars[2] = {{2020, 15000.0}, {2024, 18500.0}};
std::cout << cars[1].year << "\n"; // prints 2024
Struct members are public by default
In a struct, members are public by default, so the dot can reach them from outside the struct. In a class, members are private by default. C has no access keywords at all, so every member of a C struct can be reached with the dot.
Readers often follow up by asking whether a struct is private or public by default. The answer is in Are Struct Members Private or Public by Default?
Why not :: or []?
::looks up a name inside a namespace or a class, such asstd::cout. It does not reach the members of a variable. For that job, see What Does :: Mean in C++?[]indexes an array and picks an element, not a named member. A class can define its own[]behavior, but that is separate from the dot.
Key points to remember
- The dot (
.) connects a structure variable to its members. - The arrow (
->) does the same job through a pointer to a structure. - In an array of structs,
[]picks the element, and then the dot picks the member. - Members of a struct are public by default, so the dot reaches them from outside.