Unit IV: Structures and Unions
Course: Programming with C
Code: CADSM101
Basics of Structures and Processing
A structure is a user-defined data type in C that allows you to combine data items of different kinds. Unlike arrays, which store data of the same type, structures can group variables like an int, a float, and a char together under a single name.
- Definition: Created using the
struct keyword followed by the structure name and a list of members inside curly braces.
- Processing: Individual members are accessed using the dot operator (
.) for structure variables.
User Defined Data Types (typedef)
The typedef keyword is used to provide a new name for an existing data type. It is commonly used with structures to simplify their declaration in the code.
Example: typedef struct { int x; int y; } Point; allows you to declare a point as Point p1; instead of struct Point p1;.
Structures with Pointers and Functions
- Structures and Pointers: You can create a pointer that points to the address of a structure. When using pointers, members are accessed using the arrow operator (
->).
- Passing to Functions: Structures can be passed to functions by value (a copy is sent) or by reference (a pointer is sent). Passing by reference is more memory-efficient for large structures.
Arrays of Structures and Self-referential Structures
- Arrays of Structures: Useful for storing a list of records, such as an array of 50 students where each student has a name and a roll number.
- Self-referential Structures: A structure that contains a pointer to a structure of the same type. These are the building blocks of linked lists and trees.
Unions and Table Lookup
A Union is similar to a structure, but all its members share the same memory location.
- Memory Usage: A union's size is equal to the size of its largest member. It can only hold the value of one member at a time.
- Table Lookup: Structures are often used to create lookup tables for storing and retrieving related data efficiently.
Problem Solving with Structures and Unions
Students should be able to write programs that use these types to model real-world data.
- Managing employee or student databases.
- Performing operations on complex numbers (e.g., adding x+iy).
- Handling diverse data sets where a variable might need to store different types of data at different times using unions.
Exam Focus & Tips
- Exam Tip: A common question is the difference between Structures and Unions. Focus on the memory sharing aspect of Unions.
- Common Mistake: Forgetting the semicolon (
;) at the end of a structure definition.
- Mnemonic: Structures = Separate memory; Unions = United (shared) memory.
Frequently Asked Questions
Q: What is a self-referential structure?
A: It is a structure that has a pointer as a member which points back to the same structure type.
Q: Why use typedef with structures?
A: To create a shorter, more readable alias for the structure type, making the code cleaner.