📍 Pointer Basics and Arithmetic in C

📍 Basics of Pointers and Pointer Arithmetic in C

A pointer is a variable that stores the memory address of another variable. They are a powerful feature of C that allows efficient array handling, dynamic memory, and function calls by reference.


📘 Declaring and Using Pointers

To declare a pointer:


int *ptr; // ptr is a pointer to an integer

To assign the address of a variable to a pointer:


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

To access the value pointed by a pointer (dereferencing):


printf("%d", *ptr); // prints 10

🧠 Example: Pointer Basics


#include <stdio.h>

int main() {
    int x = 25;
    int *p = &x;

    printf("Value of x: %d\n", x);
    printf("Address of x: %p\n", &x);
    printf("Pointer p stores: %p\n", p);
    printf("Value pointed by p: %d\n", *p);

    return 0;
}

🔍 Output:

Value of x: 25
Address of x: 0x7ffc...
Pointer p stores: 0x7ffc...
Value pointed by p: 25

🔁 Pointer Arithmetic in C

Pointer arithmetic allows you to move between memory locations. It’s commonly used with arrays.

✅ Operations on pointers:

  • p + 1 → Moves the pointer to the next memory location (depending on data type size)
  • p - 1 → Moves the pointer to the previous location
  • p++, p--, p += n etc.

📌 Example: Pointer with Array


#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *p = arr; // points to arr[0]

    for(int i = 0; i < 5; i++) {
        printf("Element %d: %d\n", i, *(p + i));
    }

    return 0;
}

đŸ§Ē Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

Note: p + i moves the pointer to the next element in memory and *(p + i) gets its value.


🧩 Pointer Arithmetic Rules

  • Pointers move in steps equal to the size of the data type (e.g., 4 bytes for int).
  • Only addition/subtraction of integers is allowed with pointers.
  • You can subtract two pointers of the same type (to get distance in elements).

⚠️ Common Mistakes

  • Dereferencing a null or uninitialized pointer → causes a crash
  • Accessing memory beyond array limits → undefined behavior
  • Using wrong data type in pointer arithmetic

🧩 Practice Tasks

  1. Write a program to print array elements using pointers.
  2. Use pointer arithmetic to reverse an array.
  3. Swap two values using pointers.
  4. Find the maximum element in an array using a pointer.
pointers in c, pointer tutorial c, c programming pointer basics, pointer arithmetic in c, pointer and arrays, how to use pointer in c, dereferencing pointer in c, c pointer example

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ