3.2 Pointers, Structures, and Data Files
1. Pointers
What is a Pointer?
A pointer is a variable that stores the memory address of another variable.
Syntax:
Pointer Arithmetic
You can perform arithmetic operations on pointers to navigate through memory locations.
Valid operations:
Increment (
p++
): Moves to the next memory location of the same type.Decrement (
p--
): Moves to the previous memory location.Addition/Subtraction (
p + n
,p - n
): Adjusts the pointer byn
locations.
Example:
Passing Pointers to Functions
Pointers allow functions to modify the original value of variables.
Example:
2. Structures
What is a Structure?
A structure is a user-defined data type that groups variables of different types under a single name.
Syntax:
Declaration:
Pointer to a Structure
Accessing structure members using a pointer:
Array of Structures
Example:
3. Unions
What is a Union?
A union is similar to a structure but uses shared memory for all its members. Only one member can hold a value at any given time.
Syntax:
Key Difference from Structures
Structure: Allocates memory for all members.
Union: Allocates memory for the largest member only.
4. File Operations
File Modes
"r"
: Open a file for reading."w"
: Open a file for writing (overwrites if the file exists)."a"
: Open a file for appending (writes at the end without overwriting).
Basic File Handling Functions
fopen()
: Opens a file.fclose()
: Closes a file.fprintf()
andfscanf()
: Handles formatted input/output.fread()
andfwrite()
: Handles binary data.
Examples
Writing to a File:
Reading from a File:
Binary File Handling:
Common File Handling Errors
Forgetting to close a file.
Trying to read a file that doesn’t exist.
Using the wrong file mode.
Conclusion
Pointers, structures, unions, and file operations are essential concepts in C programming. Pointers provide direct memory manipulation and efficient data handling.
Structures enable grouping of related data, while unions optimize memory usage by sharing storage among members.
File operations facilitate data persistence and management through various modes and functions.
Last updated