🔗 Understanding Pointers and Arrays in C

🔗 Pointers and Arrays in C

In C programming, arrays and pointers are closely related. Understanding how they interact is essential for mastering C. This tutorial explains how pointers work with arrays, with step-by-step examples.


📘 Relationship Between Arrays and Pointers

When you declare an array, the array name itself acts as a pointer to the first element.


int arr[5] = {10, 20, 30, 40, 50};

Here, arr is equivalent to &arr[0].


📌 Accessing Array Elements Using Pointers


#include <stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int *p = arr;  // same as p = &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

Explanation: p + i points to the i-th element, and *(p + i) accesses the value.


🔁 Pointer Notation vs Array Notation

Array Notation Pointer Notation
arr[i] *(arr + i)
*(p + i) p[i]

All these expressions are equivalent when working with 1D arrays.


🔁 Modifying Arrays Using Pointers


#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int *p = arr;

    for(int i = 0; i < 5; i++) {
        *(p + i) = *(p + i) * 2;  // double each element
    }

    for(int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

đŸ§Ē Output:

2 4 6 8 10

⚠️ Important Notes

  • arr points to the first element, but it is a constant pointer – you cannot modify it with arr++.
  • p = arr is allowed, and p++ is valid.

🧩 Practice Exercises

  1. Write a program to calculate the sum of all elements in an array using a pointer.
  2. Reverse an array using pointer notation.
  3. Find the maximum and minimum values in an array using pointers.
  4. Write a program to copy one array to another using pointers.

🧠 Summary

  • arr is equivalent to &arr[0].
  • arr[i] == *(arr + i) and p[i] == *(p + i).
  • Pointers offer a flexible and powerful way to work with arrays.
pointers and arrays in c, c pointer array relation, pointer notation for array, pointer arithmetic with array, how pointers work with arrays in c, pointer to array c

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

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