|
|
C Pointers Made Easy - No More Confusion!
What is a Pointer?
A pointer is a variable that stores the MEMORY ADDRESS of another variable.
Basic Syntax:
int a = 42; // a variable holding value 42
int *p = &a; // p is a pointer, storing address of a
Key Operators:
& (address-of) - get the memory address of a variable
* (dereference) - get the value at that address
Example 1: Basic Pointer Usage
#include <stdio.h>
int main() {
int a = 10;
int *p = &a;
printf("Value of a: %d\n", a); // 10
printf("Address of a: %p\n", &a); // 0x7ffd...
printf("Value of p: %p\n", p); // same as &a
printf("Value at *p: %d\n", *p); // 10
// Modify a through pointer
*p = 20;
printf("New value of a: %d\n", a); // 20
return 0;
}
Example 2: Pointers and Arrays
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // array name is a pointer to first element
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d (at %p)\n", i, *(p + i), p + i);
}
return 0;
}
Example 3: Swap Two Numbers Using Pointers
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before: x=%d, y=%d\n", x, y); // 5, 10
swap(&x, &y);
printf("After: x=%d, y=%d\n", x, y); // 10, 5
return 0;
}
Example 4: Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
for (int i = 0; i < n; i++) {
arr[i] = (i + 1) * 10;
printf("arr[%d] = %d\n", i, arr[i]);
}
free(arr); // Always free allocated memory!
return 0;
}
Common Mistakes to Avoid:
1. Uninitialized pointer: int *p; *p = 10; // DANGER!
2. Null pointer: int *p = NULL; *p = 10; // CRASH!
3. Memory leak: malloc() without free()
4. Dangling pointer: using pointer after free()
Pointer Cheat Sheet:
int *p; // pointer to int
int **pp; // pointer to pointer to int
int arr[5]; // arr acts as int* (pointer to first element)
void (*func)(int); // pointer to function
Practice Exercise:
Write a function that finds the max value in an array using pointers.
void find_max(int *arr, int size, int *max) {
*max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > *max) *max = arr[i];
}
}
Master pointers and you master C! Happy coding! |
|