Arrays group values of the same type. Real records mix types: a student has a name (string), a roll number (int) and a CGPA (float). A structure (struct) groups such related values into one unit.
Defining and using a structure#
struct Student { // a new type: "struct Student"
int roll; // members (fields)
char name[30];
float cgpa;
};
Access members with the dot operator .:
101 Aarav Gupta 8.4 102 Diya Soni 9.1 Size of one Student: 40 bytes
struct अलग-अलग type के data को एक साथ जोड़ कर एक नया type बनाता है - जैसे एक student का roll (int), नाम (string) और CGPA (float)। Member तक पहुँचने के लिए dot (.) लगाते हैं: s1.name।
The size may be a little more than the sum of the members because the compiler adds padding bytes to keep members aligned in memory for speed.
typedef - a shorter name#
Notebook x4 180.00 Pen drive x1 399.00 Bag x1 850.00 TOTAL 1429.00
That was also an array of structures - the usual way to store a table of records.
Nested structures#
A structure can contain another structure:
Sunita Rao joined on 15/07/2013 Annual salary: 1344000
Pointers to structures and the -> operator#
Passing a big struct by value copies all of it. Passing a pointer is cheaper and lets the function modify the original. With a pointer, use -> instead of .:
After deposit: 7500.00 Insufficient balance Final balance: 6300.00
Unions#
A union looks like a struct, but all members share the same memory. Only one member holds a meaningful value at a time. Unions save memory in embedded systems and are used to view the same bytes in different ways.
v.i = 65 v.c = Z sizeof(union) = 4, sizeof(struct) = 12
| struct | union | |
|---|---|---|
| Memory | each member has its own space | all members share one space |
| Size | ≥ sum of members | size of the largest member |
| Use | records with many fields | one-of-several values, memory saving |
Enums - named integer constants#
An enum gives readable names to a set of integer values:
Level value: 2 Fee paid
INTERMEDIATE is 2 because counting continues from BEGINNER = 1. Enums make switch statements and status fields much easier to read than magic numbers.
Summary#
structgroups related values of different types; access members with..typedefgives a type a short name; arrays of structs store tables of records.- With a pointer to a struct, use
->; pass pointers to avoid copying and to modify. - A
unionshares one memory area among members; anenumnames integer constants.