</>
CompilerOnline
Open Interactive Editor

C Pointers & Memory Addresses

Pointers in C

Pointers are variables that store the memory address of another variable. They are one of the most powerful and complex features of C, giving developers direct control over system memory layout.

Operators:

  • &: The Address-of operator. Returns the address of a variable.
  • *: The Dereference operator. Accesses the value stored at the address pointed to.

Pointers enable dynamic memory allocation on the heap using functions like malloc() and calloc(). Once allocated, developers must manually release the memory using free() to prevent memory leaks.

Pointer arithmetic is supported, allowing you to increment or decrement pointers to traverse arrays efficiently. Incorrect use of pointers can lead to segmentation faults and buffer overflow security vulnerabilities.

Pointer Arithmetic

Since arrays occupy contiguous memory, incrementing a pointer (e.g. ptr + 1) shifts the reference forward by the byte size of its data type, accessing the next array slot.

c
#include <stdio.h>
int main() {
    int nums[3] = {10, 20, 30};
    int *ptr = nums;
    printf("First: %d, Second: %d\n", *ptr, *(ptr + 1));
    return 0;
}
c
#include <stdio.h>

int main() {
    int num = 42;
    int *ptr = &num;

    printf("Value of num: %d\n", num);
    printf("Address of num: %p\n", (void*)&num);
    printf("Value pointer points to: %d\n", *ptr);
    return 0;
}