đ 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 locationp++
,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
- Write a program to print array elements using pointers.
- Use pointer arithmetic to reverse an array.
- Swap two values using pointers.
- Find the maximum element in an array using a pointer.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ