Pointers
Pointers are C's most powerful and dangerous feature. A pointer stores a memory address. Understanding pointers is essential for dynamic memory allocation, data structures, and systems programming.
45 min•By Priygop Team•Last updated: Feb 2026
Pointers & Memory Code
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Pointer basics
int x = 42;
int *ptr = &x; // ptr stores address of x
printf("Value: %d\n", x); // 42
printf("Address: %p\n", &x); // 0x7ffee...
printf("Pointer: %p\n", ptr); // Same address
printf("Dereferenced: %d\n", *ptr); // 42
*ptr = 100; // Modify x through the pointer
printf("x is now: %d\n", x); // 100
// Pointer arithmetic
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // Array name IS a pointer to first element
printf("%d\n", *p); // 10 (first element)
printf("%d\n", *(p + 1)); // 20 (second element)
printf("%d\n", *(p + 4)); // 50 (fifth element)
// p + 1 advances by sizeof(int) bytes, not 1 byte!
// Dynamic memory allocation
int *dynamicArr = (int *)malloc(5 * sizeof(int));
if (dynamicArr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Use the memory
for (int i = 0; i < 5; i++) {
dynamicArr[i] = i * 10;
}
// Resize with realloc
dynamicArr = (int *)realloc(dynamicArr, 10 * sizeof(int));
// ALWAYS free when done
free(dynamicArr);
dynamicArr = NULL; // Prevent dangling pointer
// calloc: allocate + zero-initialize
int *zeros = (int *)calloc(100, sizeof(int));
// All 100 ints are initialized to 0
free(zeros);
// Double pointer (pointer to pointer)
int val = 5;
int *pVal = &val;
int **ppVal = &pVal;
printf("Value: %d\n", **ppVal); // 5
return 0;
}