SyntaxStudy
Sign Up
C Beginner 15 min read

Pointers in C

Pointers are one of the most powerful — and most challenging — features of C. A pointer is a variable that stores the memory address of another variable. Understanding pointers is essential for dynamic memory management and working with arrays and strings in C.

Example
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Basic pointer
    int x = 42;
    int *ptr = &x;      // ptr holds the address of x
    printf("%d\n", *ptr); // dereference: access value at address
    *ptr = 100;           // modify x through pointer
    printf("%d\n", x);    // 100

    // Pointer arithmetic
    int arr[] = {10, 20, 30, 40, 50};
    int *p = arr;  // points to first element
    for (int i = 0; i < 5; i++) {
        printf("%d ", *(p + i));  // pointer arithmetic
    }

    // Dynamic memory allocation
    int n = 5;
    int *dynArr = (int*)malloc(n * sizeof(int));
    if (dynArr == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }
    for (int i = 0; i < n; i++) dynArr[i] = i * i;
    for (int i = 0; i < n; i++) printf("%d ", dynArr[i]);
    free(dynArr);  // always free allocated memory!

    return 0;
}