A pointer is a variable whose value is a memory address. The address-of operator & gives you a variable's address; the dereference operator * gives you the value at an address. Pointers let C do pass-by-reference, build dynamic data structures, and manage memory manually — which is exactly why interviewers love them.
& and * are inverses
&x means 'the address of x'. *p means 'the value stored at the address in p'. So if p = &x, then *p is x — reading or writing *p reads or writes x itself.
Declaring and using a pointer
int x = 10;
int *p = &x; // p holds the address of x
printf("%d", *p); // 10 (value at that address)
*p = 20; // writes through the pointer
printf("%d", x); // 20 (x was changed via p)Dynamic memory: malloc and free
int *arr = (int *) malloc(5 * sizeof(int)); // allocate on the heap
if (arr != NULL) {
arr[0] = 1; // use it
free(arr); // release it — you must do this yourself
arr = NULL; // avoid a dangling pointer
}⚡ The edge
- C passes arguments by value — a function gets a copy. To let a function change the caller's variable, you pass its address and the function writes through the pointer. That's how scanf("%d", &x) works.
- You manage heap memory yourself. malloc allocates, free releases. Forgetting to free is a memory leak; using memory after freeing it is a dangling pointer; dereferencing NULL or an uninitialised pointer crashes.
Worked example
How do you swap two integers using pointers in C?
- C is pass-by-value, so passing the ints themselves only swaps copies — useless to the caller.
- Pass their addresses instead: void swap(int *a, int *b).
- Inside, use a temp and dereference: int t = *a; *a = *b; *b = t; — this writes through to the originals.
Answer: Pass addresses (int *a, int *b) and swap through dereferences: t=*a; *a=*b; *b=t; — because C is pass-by-value.
Worked example
What is the difference between malloc and calloc?
- Both allocate heap memory and return a pointer.
- malloc(n) allocates n bytes and leaves them uninitialised (garbage).
- calloc(count, size) allocates and zero-initialises the memory. Both are released with free.
Answer: malloc allocates uninitialised memory; calloc allocates and zero-initialises it. Both are freed with free.
⚠ Watch out
- Uninitialised (wild) pointers point anywhere — always initialise, often to NULL.
- Memory leak: every malloc needs a matching free.
- Dangling pointer: using memory after free, or returning the address of a local variable, is undefined behaviour.