📍 Pointers in C - Complete Guide

Pointer in Detail

What is a Pointer?

A pointer is a variable that stores the memory address of another variable.

int a = 10;
                    int *ptr = &a; // ptr now holds the address of variable a
Pointer Subtopics

Why Use Pointers?

Pointer Terminology

int x = 5;
int *p = &x;  // address of x
printf("%d", *p); // value at address (dereferencing)

How Pointers Work in Memory

When a variable is declared, it's stored at a specific memory location. A pointer stores this address.

For example:

int a = 5;
int *ptr = &a;
printf("Address: %p\n", ptr);
printf("Value: %d\n", *ptr);

Pointer to Pointer

A pointer that stores the address of another pointer.

int x = 10;
int *p = &x;
int **pp = &p;

printf("Value: %d", **pp);

Pointer Arithmetic

Pointers can be incremented/decremented to move across memory (especially arrays).

int arr[] = {1, 2, 3};
int *p = arr;

printf("%d", *(p + 1)); // prints 2

Pointers and Arrays

Array names are constant pointers. You can iterate over arrays using pointers.

int arr[3] = {10, 20, 30};
int *p = arr;

for(int i = 0; i < 3; i++) {
    printf("%d ", *(p + i));
}

Pointers and Functions

Pointers are used to pass arguments by reference.

void modify(int *p) {
    *p = 100;
}

int main() {
    int x = 10;
    modify(&x);
    printf("%d", x);  // 100
}

Dynamic Memory Allocation

Using pointers and malloc/calloc to allocate memory at runtime.

int *ptr = (int*) malloc(sizeof(int));
*ptr = 50;
printf("%d", *ptr);
free(ptr);

Practice these pointer assignments


Pointer Assignments

Pointers in Data Structures

Real Life Analogy

📚 References