Structures and Unions
Learn C structures and unions from a JavaScript perspective. Understand struct, union, memory layout, and compare with JavaScript objects.
Structures and Unions
1. Introduction
From JavaScript Objects to C Structures
In JavaScript, objects are dynamic collections of key-value pairs, supporting flexible property addition and deletion. In C, structures (struct
) provide a way to group related variables under one name, with a fixed memory layout. Unions (union
) allow different data types to share the same memory location.
💡 Key Concept: C structures and unions are essential for modeling complex data, memory optimization, and system-level programming.
2. Syntax Comparison
3. Unions
4. Common Pitfalls
- C structs have fixed layout; no dynamic property addition.
- Unions share memory; only one member is valid at a time.
- String handling requires care (use
strcpy
, buffer size checks). - Memory alignment and padding may affect struct size.
5. Exercises
- Define a struct
Book
with title, author, and price. Write code to input and print book info. - Create a union that can store either an
int
, afloat
, or achar[10]
. Demonstrate usage. - Compare memory usage of a struct and a union with the same members.
6. Performance Analysis
- Structs provide efficient, cache-friendly data layout.
- Unions save memory when only one member is used at a time.
- Improper use of unions can lead to undefined behavior.
Summary: C structures and unions are powerful tools for modeling data and optimizing memory. Unlike JavaScript objects, they have fixed layouts and require explicit memory management. Mastery of these concepts is essential for system programming and performance-critical applications.
Functions and Stack Management
Learn C functions and stack management from a JavaScript perspective. Understand function parameters, stack frames, recursion, function pointers, and memory management.
Dynamic Memory Allocation
Learn C dynamic memory allocation from a JavaScript perspective. Understand malloc, free, memory leaks, and compare with JavaScript garbage collection.