C PROGRAMMING • Intermediate

C Pointers

A pointer is a variable that stores the memory address of another variable. Pointers are the most powerful — and most feared — feature of C. They give you direct access to memory, enabling efficient data structures, dynamic memory allocation, and low-level system programming.

What is a Pointer?

Every variable in memory has an address. A pointer stores that address, letting you access the value indirectly. This is called indirection.

int x = 10;
int *ptr = &x;    // ptr stores the address of x

printf("Value of x: %d\n", x);          // 10
printf("Address of x: %p\n", &x);       // 0x7ffd5e3a4b2c (some hex)
printf("ptr holds: %p\n", ptr);          // Same address
printf("Value via ptr: %d\n", *ptr);     // 10

Two Key Operators

  • & (address-of) — Gives the memory address of a variable.
  • * (dereference) — Gives the value stored at that address. Also used to declare pointer variables.

Declaring a Pointer

// Syntax: data_type *pointer_name;

int *p1;        // pointer to int
float *p2;      // pointer to float
char *p3;       // pointer to char
double *p4;     // pointer to double

// Multiple pointers
int *a, *b, *c;

// vs — this declares one pointer and two ints
int *d, e, f;
⚠ Common Mistake

int *a, b; declares a as a pointer and b as an int — NOT two pointers. Always use int *a, *b; if you want two pointers.

Initializing a Pointer

int x = 10;

int *ptr = &x;      // ✅ initialize at declaration
// or
int *ptr2;
ptr2 = &x;           // ✅ initialize later

// ❌ NEVER do this — pointer to garbage
int *bad;
// *bad = 5;   // undefined behavior, likely crash

Dereferencing a Pointer

Dereferencing means accessing the value the pointer points to.

int x = 10;
int *ptr = &x;

printf("%d\n", *ptr);   // 10

*ptr = 20;              // Change x via the pointer
printf("%d\n", x);      // 20
printf("%d\n", *ptr);   // 20

Pointer Size

All pointers are the same size — typically 8 bytes on 64-bit systems, 4 bytes on 32-bit.

printf("%lu\n", sizeof(int*));    // 8
printf("%lu\n", sizeof(char*));   // 8
printf("%lu\n", sizeof(float*));  // 8
// All the same size regardless of type

NULL Pointer

A pointer that points to nothing. Always initialize unused pointers to NULL to avoid bugs.

int *ptr = NULL;

if (ptr != NULL) {
    printf("%d\n", *ptr);   // only safe if not NULL
}

// NULL is defined in <stddef.h> as (void*)0
💡 Academy Tip

Always check if a pointer is NULL before dereferencing. Dereferencing NULL causes a segmentation fault — a very common bug in C.

Pointer Arithmetic

You can do arithmetic on pointers — but it's not simple math. The compiler scales by the size of the data type.

int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;    // points to arr[0]

printf("%d\n", *ptr);      // 10
printf("%d\n", *(ptr+1));  // 20 (moves 4 bytes forward)
printf("%d\n", *(ptr+2));  // 30

ptr++;                     // now points to arr[1]
printf("%d\n", *ptr);      // 20

Valid Operations

  • ptr++, ptr-- — move to next/prev element
  • ptr + n — move n elements forward
  • ptr - n — move n elements backward
  • ptr2 - ptr1 — distance between two pointers
  • Comparison: ptr1 == ptr2, ptr1 < ptr2

Invalid Operations

  • ptr + ptr — adding two pointers is nonsense
  • ptr * 2, ptr / 2 — not allowed

Pointers and Arrays

An array name is essentially a pointer to its first element.

int arr[] = {10, 20, 30, 40, 50};

// These are equivalent:
printf("%d\n", arr[2]);     // 30
printf("%d\n", *(arr+2));   // 30

// Access array using pointer
int *ptr = arr;
for (int i = 0; i < 5; i++) {
    printf("%d ", *(ptr + i));
}

Array name vs Pointer

int arr[5];
int *ptr = arr;

// Same:
arr[2] === *(arr + 2) === *(ptr + 2) === ptr[2]

// Different:
sizeof(arr) = 20;    // whole array
sizeof(ptr) = 8;     // just a pointer

Pointers and Functions

C passes arguments by value. To modify a variable inside a function, pass its address.

Without Pointer (doesn't work)

void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 10, y = 20;
    swap(x, y);
    printf("x=%d y=%d\n", x, y);   // 10, 20 — NOT swapped
    return 0;
}

With Pointer (works)

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 10, y = 20;
    swap(&x, &y);           // pass addresses
    printf("x=%d y=%d\n", x, y);   // 20, 10 — swapped ✅
    return 0;
}

Pointer to Pointer

A pointer that stores the address of another pointer.

int x = 10;
int *ptr = &x;
int **pptr = &ptr;

printf("%d\n", **pptr);   // 10

// Visual:
// pptr → ptr → x → 10

Pointers and Strings

char *str = "Varanasi";     // string literal (read-only)

printf("%s\n", str);         // Varanasi
printf("%c\n", str[0]);      // V
printf("%c\n", *(str+1));    // a

// Iterate
while (*str != '\0') {
    printf("%c", *str);
    str++;
}

Pointer to Constant vs Constant Pointer

// Pointer to constant — cannot change *p, can change p
const int *p1;
int const *p1;   // same

// Constant pointer — cannot change p, can change *p
int * const p2 = &x;

// Both constant — cannot change either
const int * const p3 = &x;

Dynamic Memory Allocation

Pointers enable dynamic memory allocation using malloc, calloc, and free.

#include <stdlib.h>

// Allocate 5 ints at runtime
int *arr = (int*) malloc(5 * sizeof(int));

if (arr == NULL) {
    printf("Memory allocation failed\n");
    return 1;
}

// Use it
for (int i = 0; i < 5; i++) {
    arr[i] = (i + 1) * 10;
}

// Print
for (int i = 0; i < 5; i++) {
    printf("%d ", arr[i]);
}

// Free it — always!
free(arr);
arr = NULL;
⚠ Memory Leak Warning

Every malloc() must have a matching free(). Forgetting to free causes memory leaks — the memory stays locked until the program ends. Always free dynamically allocated memory.

Common Pointer Mistakes

1. Dereferencing uninitialized pointer

int *ptr;
*ptr = 10;   // ❌ Undefined behavior — likely crash

2. Dereferencing NULL

int *ptr = NULL;
*ptr = 10;   // ❌ Segfault

3. Forgetting to free memory

int *arr = malloc(100);
// ... use it ...
// ❌ No free(arr) → memory leak

4. Using freed pointer (dangling pointer)

int *ptr = malloc(sizeof(int));
free(ptr);
*ptr = 10;   // ❌ Undefined behavior

Real-World Example — Swap and Sum

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void calculateSum(int *arr, int size, int *result) {
    *result = 0;
    for (int i = 0; i < size; i++) {
        *result += arr[i];
    }
}

int main() {
    int x = 10, y = 20;

    printf("Before swap: x=%d, y=%d\n", x, y);
    swap(&x, &y);
    printf("After swap: x=%d, y=%d\n", x, y);

    int numbers[] = {10, 20, 30, 40, 50};
    int sum;
    calculateSum(numbers, 5, &sum);
    printf("Sum: %d\n", sum);

    return 0;
}

Output

Before swap: x=10, y=20
After swap: x=20, y=10
Sum: 150
📝 Try Yourself

1. Print the value and address of a variable using a pointer.
2. Swap two numbers using pointers.
3. Traverse an array using pointer arithmetic (no []).
4. Find the sum of array elements using a pointer to the array.
5. Dynamically allocate memory for 5 integers, fill them, print them, then free.
6. Demonstrate pointer to pointer with a simple example.

Quick Revision

  • Pointer stores memory address of another variable.
  • & = address-of; * = dereference.
  • Initialize pointer before use; NULL if not pointing anywhere.
  • Pointer size is same regardless of type (8 bytes on 64-bit).
  • Array name is a pointer to first element.
  • arr[i] = *(arr+i).
  • Pass &var to modify var inside function.
  • Pointer to pointer uses **.
  • Use malloc() for dynamic memory; always free().
  • NULL dereference causes segmentation fault.

Interview Questions

Q: What is a pointer?

A: A pointer is a variable that stores the memory address of another variable. It allows indirect access to memory, enabling efficient data structures and system-level programming.

Q: Difference between & and *?

A: & (address-of) returns the memory address of a variable. * (dereference) returns the value stored at a pointer's address. They're inverse operations.

Q: What is a NULL pointer?

A: A pointer that doesn't point to any valid memory location. It's often used as a sentinel value to indicate "no pointer" or "empty". Dereferencing NULL causes a segmentation fault.

Q: What is pointer arithmetic?

A: Arithmetic operations on pointers — addition, subtraction, increment, decrement. The compiler scales by the size of the data type. ptr + 1 moves by sizeof(type) bytes, not 1 byte.

Q: Difference between array and pointer?

A: An array is a fixed block of contiguous memory with a name. A pointer is a variable that stores an address. Array name decays to a pointer when passed to a function, but sizeof(arr) differs — array gives total size, pointer gives its own size.

Q: What is a dangling pointer?

A: A pointer that points to memory that has been freed or gone out of scope. Using it causes undefined behavior. Always set pointers to NULL after free().

Q: What is a void pointer?

A: A void* pointer can point to any data type. It's used for generic programming (e.g., malloc returns void*). It cannot be dereferenced directly — you must cast it to the correct type first.

Q: How is memory allocated dynamically in C?

A: Using malloc() (uninitialized memory), calloc() (zeroed memory), and realloc() (resize). Always pair with free() to avoid memory leaks.

Want to Master C Programming?

Join our C Programming course in Varanasi — practical classes and career support at our Sarnath centre.

Ask on WhatsApp
Chat with us