C Pointers
Overview
Pointers are one of the most powerful and important features in C language. They allow direct memory manipulation and are the foundation of many advanced C programming concepts.
Basic Concepts
What is a Pointer?
A pointer is a variable that stores the memory address of another variable.
c
int x = 10;
int *ptr = &x; // ptr stores the address of xPointer Declaration and Initialization
c
int *p; // Declare a pointer to int
int x = 5;
p = &x; // Initialize pointer with address of xUsing Pointers
c
int x = 10;
int *ptr = &x;
printf("Value of x: %d\n", x); // Output: 10
printf("Address of x: %p\n", &x); // Output memory address
printf("Value of ptr: %p\n", ptr); // Output memory address
printf("Value pointed by ptr: %d\n", *ptr); // Output: 10Pointer Arithmetic
c
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("%d\n", *ptr); // 10
printf("%d\n", *(ptr+1)); // 20
printf("%d\n", *(ptr+2)); // 30Pointers and Arrays
c
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr;
for(int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i));
}Best Practices
- Always initialize pointers before using them
- Check for NULL before dereferencing
- Free allocated memory to avoid memory leaks
- Use const pointers when data shouldn't be modified