c2cedge
C, Java & Python · B — C Essentials

C: Pointers & Memory

Pointers are the soul of C and the question every C interview asks. A pointer is just a variable that holds an address — master that and the rest is mechanics.

Test weight: Very high (C)Skill: Addresses & memoryDifficulty: Medium–Hard

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?
  1. C is pass-by-value, so passing the ints themselves only swaps copies — useless to the caller.
  2. Pass their addresses instead: void swap(int *a, int *b).
  3. Inside, use a temp and dereference: int t = *a; *a = *b; *b = t; — this writes through to the originals.
Worked example
What is the difference between malloc and calloc?
  1. Both allocate heap memory and return a pointer.
  2. malloc(n) allocates n bytes and leaves them uninitialised (garbage).
  3. calloc(count, size) allocates and zero-initialises the memory. Both are released 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.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms