langShiftlangShift

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

  1. Define a struct Book with title, author, and price. Write code to input and print book info.
  2. Create a union that can store either an int, a float, or a char[10]. Demonstrate usage.
  3. 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.