Pointer Basics
Introduction to Pointers
In C programming, a pointer is a variable that stores the memory address of another variable. Understanding pointers is crucial for efficient memory management and advanced programming techniques.
Memory and Address Concept
Pointers allow direct manipulation of memory addresses. Every variable in C is stored at a specific memory location with a unique address.
int x = 10;
int *ptr = &x; // ptr stores the memory address of x
Pointer Declaration and Initialization
Pointers are declared using the asterisk (*) symbol:
int *ptr; // Pointer to an integer
char *str; // Pointer to a character
double *dptr; // Pointer to a double
Types of Pointers
Pointer Type |
Description |
Example |
Integer Pointer |
Stores address of integer variables |
int *ptr |
Character Pointer |
Stores address of characters |
char *str |
Void Pointer |
Can store address of any type |
void *generic_ptr |
Pointer Operations
Address-of Operator (&)
Retrieves the memory address of a variable.
int x = 42;
int *ptr = &x; // ptr now contains x's memory address
Dereference Operator (*)
Accesses the value stored at a pointer's address.
int x = 42;
int *ptr = &x;
printf("%d", *ptr); // Prints 42
Memory Visualization
graph TD
A[Variable x] -->|Memory Address| B[Pointer ptr]
B -->|Dereference| C[Actual Value]
Common Pointer Pitfalls
- Uninitialized pointers
- Null pointer dereferencing
- Memory leaks
- Dangling pointers
Best Practices
- Always initialize pointers
- Check for NULL before dereferencing
- Free dynamically allocated memory
- Use const for read-only pointers
Practical Example
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", (void*)&x);
printf("Value of ptr: %p\n", (void*)ptr);
printf("Value pointed by ptr: %d\n", *ptr);
return 0;
}
By mastering pointers, you'll unlock powerful programming techniques in C. LabEx recommends practicing these concepts to build strong memory management skills.