bca class pointer
bca class pointer
Characteristics of Pointers:
Memory Address: A pointer holds the address of a variable or object.
Dereferencing: The * operator is used to access or modify the value at the
memory location pointed to by the pointer.
Type-Specific: Pointers are type-specific, meaning a pointer to an int
cannot be used as a pointer to a float without casting.
Null Pointer: A pointer can be initialized to NULL or nullptr to indicate it
does not point to any valid memory.
Dynamic Allocation: Pointers enable the allocation of memory at runtime
using functions like malloc, calloc, new, and delete.
* and & Operators:
& (Address-of Operator):
Retrieves the address of a variable.
Example:
int a = 10;
int *p = &a; // p now stores the address of a
* (Dereference Operator):
Accesses the value at the memory location pointed to by the pointer.
Example:
int a = 10;
int *p = &a;
printf("%d", *p); // Output: 10
Pointer Type Declaration and Assignment:
Pointers are declared by placing * before the pointer name. The type
indicates what kind of data the pointer will point to.
Declaration:
int *p; // Pointer to an integer
char *c; // Pointer to a character
Assignment:
int a = 20;
int *p = &a; // p stores the address of a
Pointer Arithmetic
Pointer arithmetic allows you to navigate through memory. Operations
include addition, subtraction, and comparison.
Incrementing: Moves to the next memory location based on the size of the
data type.
int arr[] = {1, 2, 3};
int *p = arr;
p++; // Now points to the second element of the array
Decrementing: Moves to the previous memory location.
Difference: Finds the number of elements between two pointers.
int main() {
int a = 5;
increment(&a);
printf("%d", a); // Output: 6
}
Passing Pointers to Functions:
Pointers can be passed to functions to save memory or manipulate arrays
or structures.
int main() {
int (*funcPtr)(int, int) = &add;
printf("%d", funcPtr(5, 10)); // Output: 15
}
Pointer to Pointer:
A pointer to a pointer stores the address of another pointer.
int a = 10;
int *p = &a;
int **pp = &p;
printf("%d", **pp); // Output: 10
Best Uses of Pointers:
Dynamic Memory Allocation: Allocate memory at runtime using malloc,
calloc, or new.
Efficient Array Handling: Use pointers to iterate through arrays efficiently.
Function Call Optimization: Pass large data structures by reference instead
of by value.
Implementation of Data Structures: Essential for linked lists, trees, and
graphs.
Hardware Interaction: Manipulate memory-mapped I/O registers directly.