Here's a C program that demonstrates various aspects of how pointers work:
c
#include <stdio.h>
int main() {
// Basic pointer declaration and usage
int num = 42;
int *ptr = # // ptr stores the address of num
printf("=== Basic Pointer Usage ===\n");
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", (void*)&num);
printf("Value of ptr (address it holds): %p\n", (void*)ptr);
printf("Value pointed to by ptr: %d\n", *ptr);
// Modifying value through pointer
*ptr = 100;
printf("\nAfter *ptr = 100:\n");
printf("Value of num: %d\n", num); // num is now 100
// Pointer arithmetic with arrays
int arr[] = {10, 20, 30, 40, 50};
int *arrPtr = arr; // array name is a pointer to first element
printf("\n=== Pointer Arithmetic ===\n");
printf("Array elements using pointer arithmetic:\n");
for (int i = 0; i < 5; i++) {
printf("*(arrPtr + %d) = %d, Address: %p\n",
i, *(arrPtr + i), (void*)(arrPtr + i));
}
// Pointer to pointer
int **ptrToPtr = &ptr;
printf("\n=== Pointer to Pointer ===\n");
printf("Value of ptrToPtr: %p\n", (void*)ptrToPtr);
printf("Value pointed by ptrToPtr (address of num): %p\n", (void*)*ptrToPtr);
printf("Value pointed by *ptrToPtr: %d\n", **ptrToPtr);
// Dynamic memory allocation
int *dynamicPtr = (int*)malloc(sizeof(int));
if (dynamicPtr != NULL) {
*dynamicPtr = 999;
printf("\n=== Dynamic Memory ===\n");
printf("Dynamically allocated value: %d\n", *dynamicPtr);
printf("Address of dynamic memory: %p\n", (void*)dynamicPtr);
free(dynamicPtr); // Don't forget to free!
}
// Function pointers
int add(int a, int b) { return a + b; }
int (*funcPtr)(int, int) = add;
printf("\n=== Function Pointer ===\n");
printf("Result of function through pointer: %d\n", funcPtr(5, 3));
// NULL pointer
int *nullPtr = NULL;
printf("\n=== NULL Pointer ===\n");
printf("NULL pointer value: %p\n", (void*)nullPtr);
return 0;
}
This program demonstrates:
Basic pointer operations: Declaring a pointer, getting an address with &, and dereferencing with *
Pointer modification: Changing the value at the memory location a pointer points to
Pointer arithmetic: Moving through array elements by incrementing the pointer
Pointer to pointer: A pointer that stores the address of another pointer
Dynamic memory: Using malloc() to allocate memory at runtime
Function pointers: Storing and calling functions through pointers
NULL pointers: The concept of a pointer that points to nothing
Key concepts to remember:
& gets the address of a variable
* dereferences a pointer (gets the value at that address)
Pointers store memory addresses
Pointer arithmetic moves by the size of the pointed-to type