Pointer Fundamentals
What is a Pointer?
In C programming, a pointer is a variable that stores the memory address of another variable. Unlike regular variables that directly hold data, pointers provide a way to indirectly access and manipulate memory.
graph LR
A[Variable] --> B[Memory Address]
B --> C[Pointer]
Basic Pointer Declaration and Initialization
Pointers are declared using an asterisk (*) followed by the pointer name:
int *ptr; // Pointer to an integer
char *charPtr; // Pointer to a character
double *doublePtr; // Pointer to a double
Address-of Operator (&) and Dereferencing Operator (*)
Getting Memory Address
int x = 10;
int *ptr = &x; // ptr now holds the memory address of x
Dereferencing a Pointer
int x = 10;
int *ptr = &x;
printf("Value of x: %d\n", *ptr); // Accessing the value stored at the address
Pointer Types and Memory Allocation
Pointer Type |
Size (on 64-bit systems) |
Description |
char* |
8 bytes |
Stores address of a character |
int* |
8 bytes |
Stores address of an integer |
double* |
8 bytes |
Stores address of a double |
Common Pointer Operations
Pointer Arithmetic
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Points to the first element
printf("%d\n", *ptr); // 10
printf("%d\n", *(ptr + 1)); // 20
printf("%d\n", *(ptr + 2)); // 30
Null Pointers
int *ptr = NULL; // Always initialize unassigned pointers to NULL
Potential Pitfalls
- Uninitialized pointers
- Dereferencing NULL pointers
- Memory leaks
- Buffer overflows
Best Practices
- Always initialize pointers
- Check for NULL before dereferencing
- Use dynamic memory allocation carefully
- Free dynamically allocated memory
Example: Practical Pointer Usage
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
Learning with LabEx
To practice and master pointer concepts, LabEx provides interactive C programming environments where you can experiment safely with pointer operations.