C Programming with Pointers Notes
Introduction to Pointers
- Pointers allow for direct manipulation of memory by storing addresses of variables, enhancing function performance through pass-by-reference.
Concept of Swapping Values
- Swapping values typically requires creating reusable functions.
- A function like
void swap(a, b)highlights the necessity of passing variables correctly.
Pass-By-Value vs Pass-By-Reference
Pass-By-Value:
- The function parameter is a copy of the actual argument.
- Example: Calling
swap()uses copies, not modifying the original.
Pass-By-Reference:
- A function can modify the variable directly if passed its memory address.
- Achieved using the address operator
&in C.
Understanding Addresses and Memory
- Variables are stored in memory locations with unique addresses.
- Scanf function:
- Uses
&to denote where in memory to store user inputs, making it capable of modifying that location directly.
- Uses
Declaring Pointers
- A pointer is a variable that stores the address of another variable.
- Syntax for declaring a pointer:
data_type *pointer_name;- Example:
int *ptr;declares a pointer to an integer.
Important Pointer Syntax and Behavior
The * (asterisk) indicates a pointer. It is crucial to differentiate its usage in declarations from its role in dereferencing (accessing value at an address).
Dereference Operator (
*): Used to access or change the value at the address a pointer holds.Two contexts of the dereferencing operator:
- Left Side: Change the value at the memory location.
- Right Side: Retrieve the value stored at that location.
Common Errors with Pointers
- Issues may arise if pointers are not correctly initialized or dereferenced.
- Possible access violations if pointers reference illegal memory locations (garbage values).
Safety and NULL Pointers
- Initialize pointers to
NULLto prevent accidental access to invalid memory locations. - Setting pointers to
NULLafter use can prevent dangling pointers.
Function Parameters and Pointers
- Functions can accept pointers as parameters to modify passed values:
- Example:
void increment(int *ptr)modifies the integer by referencing its address.
- Example:
Using Pointers with Arrays
- When passing an array to a function, it decays to a pointer pointing to its first element.
- Example:
void reset_array(int *arr, int size)can reset each value of the provided array effectively.
Conclusion
- Understanding pointers is essential for efficient programming in C.
- They facilitate extensive memory manipulation, thereby enhancing program efficiency and flexibility.
Reminder
- When working with memory, always be cautious to avoid common runtime errors and ensure safe access.