C Structs and Pointers
1. Pointer to a Structure
-
You can create a pointer that points to a structure variable.
-
Useful when passing structures to functions or for dynamic memory allocation.
Syntax:
-
Access members using arrow
->operator instead of dot..
2. Example: Basic Structure Pointer
Output:
ptr->memberis equivalent to(*ptr).member.
3. Using Pointer with Array of Structures
Output:
4. Passing Structure Pointer to Function
-
Passing a structure pointer to a function avoids copying the whole structure.
Output:
5. Dynamic Memory Allocation with Struct Pointer
-
mallocallocates memory dynamically for a structure. -
Always use
free()to release memory.
6. Key Points About Structs and Pointers
-
Use
struct StructName *ptrto create a structure pointer. -
Access members using arrow
->(ptr->member). -
Arrays of structures can be accessed using pointer arithmetic (
(ptr+i)->member). -
Passing structure pointers to functions saves memory.
-
Combine with
mallocfor dynamic memory allocation. -
(*ptr).memberis equivalent toptr->member(less convenient).
