C Pointers
A pointer is a variable that stores the address of another variable. & gives an address; * dereferences it (accesses the value at that address).
#include <stdio.h>
int main() {
int x = 42;
int *p = &x;
printf("x = %d, *p = %d\n", x, *p);
*p = 100; // changes x through the pointer
printf("x is now %d\n", x);
int a[] = {10, 20, 30};
int *q = a;
printf("%d %d %d\n", *q, *(q + 1), q[2]); // pointer arithmetic
return 0;
}
x = 42, *p = 42
x is now 100
10 20 30
Dynamic Memory Allocation
| Function | Purpose |
|---|---|
malloc(n) | Allocate n bytes (uninitialised) |
calloc(k, size) | Allocate k blocks, zero-initialised |
realloc(p, n) | Resize a block |
free(p) | Release memory |
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *arr = (int *) malloc(n * sizeof(int));
if (arr == NULL) return 1;
for (int i = 0; i < n; i++) arr[i] = (i + 1) * (i + 1);
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
free(arr);
return 0;
}
1 4 9 16 25
Pointer pitfallsDangling pointers (used after
free), memory leaks (never freed) and wild pointers (uninitialised) are common bugs.Track your progress through the C course