Skip to content

C Pointers

Overview

Pointers are one of the most powerful and important features in C language. They allow direct memory manipulation and are the foundation of many advanced C programming concepts.

Basic Concepts

What is a Pointer?

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

c
int x = 10;
int *ptr = &x;  // ptr stores the address of x

Pointer Declaration and Initialization

c
int *p;        // Declare a pointer to int
int x = 5;
p = &x;        // Initialize pointer with address of x

Using Pointers

c
int x = 10;
int *ptr = &x;

printf("Value of x: %d\n", x);      // Output: 10
printf("Address of x: %p\n", &x);    // Output memory address
printf("Value of ptr: %p\n", ptr);    // Output memory address
printf("Value pointed by ptr: %d\n", *ptr); // Output: 10

Pointer Arithmetic

c
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;

printf("%d\n", *ptr);     // 10
printf("%d\n", *(ptr+1)); // 20
printf("%d\n", *(ptr+2)); // 30

Pointers and Arrays

c
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr;

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

Best Practices

  1. Always initialize pointers before using them
  2. Check for NULL before dereferencing
  3. Free allocated memory to avoid memory leaks
  4. Use const pointers when data shouldn't be modified

Content is for learning and research only.