Back to course

Accessing Structure Members and Array of Structures

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 42: Accessing Structure Members and Array of Structures

Accessing Members (. operator)

We use the dot operator (.) to access individual members of a structure variable.

c struct Book { char title[100]; float price; };

int main() { struct Book b1;

// Accessing and assigning values
b1.price = 29.99;
strcpy(b1.title, "The C Handbook");

// Accessing and printing values
printf("Book: %s, Price: %.2f\n", b1.title, b1.price);
return 0;

}

Array of Structures

We can declare an array where each element is a structure. This is useful for managing lists of records (e.g., a list of students or employees).

c struct Product { int product_id; float cost; };

// Array of 5 product structures struct Product inventory[5];

// Accessing members in an array of structures inventory[0].product_id = 1001; inventory[0].cost = 5.99;

// Looping through the array for (int i = 0; i < 5; i++) { // Take input or process inventory[i] printf("Product %d cost: %.2f\n", inventory[i].product_id, inventory[i].cost); }