Structure Declaration
Basic Concepts
Structures group values of different types under a single name. Each value is called a member variable.
Declaration Syntax
struct tag {
member_list;
} variable_list;
Example: A student structure with name, age, gender, and height:
struct Student {
char name[20];
int age;
char gender[2];
float height;
};
Anonymous Structures
Anonymous structures lack a tag and can only be used once:
struct {
int a;
char b;
float c;
} x;
Self-Referential Structures
Used in linked lists, where a node points to another node:
struct Node {
int data;
struct Node* next;
};
Structure Variable Definition and Initialization
Variables can be defined during or after declaration:
struct Student s1 = {"Alice", 20, "F", 165.5};
Nested structures initialize inner structures with braces:
struct Point {
int x;
int y;
};
struct Shape {
char type;
struct Point center;
};
struct Shape circle = {'C', {10, 20}};
Structure Member Access
Member are accessed using . or -> for pointers:
struct Student s1 = {"Bob", 22, "M", 180.0};
struct Student* ptr = &s1;
printf("Name: %s\n", ptr->name);
Structure Memory Alignment
Memory alignment ensures efficient access. Rules:
- First member at offset 0.
- Subsequent members align to their size or compiler default.
- Total size is a multiple of the largest alignment.
Example:
struct AlignTest {
char a;
int b;
char c;
};
// Size: 12 bytes (due to padding)
Bit Fields
Bit fields optimize memory by specifying member sizes in bits:
struct BitField {
unsigned int flag1 : 1;
unsigned int flag2 : 3;
};
Enumerations
Enums define named constants:
enum Weekday {MON, TUE, WED, THU, FRI, SAT, SUN};
enum Weekday day = MON;
Unions
Unions share memory among members:
union Data {
int i;
float f;
char str[20];
};
union Data data;
data.i = 10;
printf("%d\n", data.i);
Practical Applications
- Memory Alignment: Critical for performance in embedded systems.
- Bit Fields: Useful in network protocols for compact data reprseentation.
- Unions: Save memory when only one member is active at a time.
Example: Checikng Endianness
int checkEndian() {
union {
int i;
char c;
} test;
test.i = 1;
return test.c; // Returns 1 for little-endian
}