Concept Flow - Accessing structure members
Define struct
Create struct variable
Access member using . or ->
Use member value
End
This flow shows how to define a struct, create a variable, access its members, and use those values.
struct Point {
int x;
int y;
};
struct Point p = {3, 4};
int sum = p.x + p.y;| Step | Action | Variable/Member Access | Value | Result/Output |
|---|---|---|---|---|
| 1 | Define struct Point | - | - | Struct type Point created with members x and y |
| 2 | Create variable p | p | x=3, y=4 | Variable p initialized with x=3 and y=4 |
| 3 | Access p.x | p.x | 3 | Value 3 retrieved |
| 4 | Access p.y | p.y | 4 | Value 4 retrieved |
| 5 | Calculate sum | p.x + p.y | 3 + 4 | sum = 7 |
| 6 | End | - | - | Program ends |
| Variable | Start | After Step 2 | After Step 5 |
|---|---|---|---|
| p.x | - | 3 | 3 |
| p.y | - | 4 | 4 |
| sum | - | - | 7 |
struct StructName { memberType memberName; };
struct StructName var = {values};
Access members with var.memberName (dot operator).
If pointer to struct, use pointer->memberName (arrow operator).
Use members to read or assign values.struct Point { int x; int y; } p;, which is the correct way to assign 10 to member x?p is a structure variable, not a pointer.p.x = 10; is correct.struct Person {
char name[10];
int age;
};
int main() {
struct Person p = {"Amy", 25};
printf("%s %d", p.name, p.age);
return 0;
}p is initialized with "Amy" for name and 25 for age.printf prints p.name as a string and p.age as an integer, so output is Amy 25.struct Data {
int id;
float value;
};
int main() {
struct Data d;
d->id = 5;
d.value = 3.14;
return 0;
}d is a structure variable, not a pointer, so d->id is incorrect.d.id = 5; is correct.struct Employee {
char name[20];
int id;
};
int main() {
struct Employee emp1 = {"John", 101};
struct Employee *ptr = &emp1;
ptr->id = 202;
printf("%s %d", emp1.name, emp1.id);
return 0;
}
What will be the output?ptr points to emp1, so ptr->id changes emp1.id.ptr->id = 202;, emp1.id becomes 202. Printing emp1.name and emp1.id outputs John 202.Pass the test and this pattern moves unknown