Pointer and Arrays
In C, arrays and pointers are closely related. An array name decays into a pointer to its first element. For example:
int arr[5] = {1,2,3,4,5};
int *ptr = arr; // ptr points to arr[0]
Pointer Arithmetic
Pointer arithmetic allows operations like addition/subtraction with pointers:
ptr++
moves to the next elementptr--
moves to the previous element*ptr + 1
increments the value at the addressptr + 2
moves two elements forward
Function Pointers
Function pointers store addresses of functions. Example:
void (*funcPtr)(int) = &myFunction;
funcPtr(10); // Calls myFunction with argument 10
Use them for callbacks or dynamic function invocation.
Pointer to Pointer
A pointer that points to another pointer:
int x = 42;
int *ptr = &x;
int **pptr = &ptr;
printf("%d", **pptr); // Outputs 42
Best Practices 🛡️
- Always initialize pointers before use
- Use
const
for pointer-to-constant data - Avoid dangling pointers by managing memory carefully
- Prefer
nullptr
overNULL
in modern C++