Pointer in C
A pointer is a variable that stores the memory address of another variable. Pointers are powerful
and essential in C programming for direct memory manipulation, dynamic memory allocation,
and efficient data handling.
---
Declaration and Initialization of Pointer Variable
1. Declaration:
Use the * symbol to declare a pointer variable.
Syntax:
data_type *pointer_name;
Example:
int *p; // Declares a pointer to an integer
2. Initialization:
Assign the address of a variable to the pointer using the & operator.
Example:
int a = 10;
int *p = &a; // Pointer p holds the address of variable a
---
Pointer Arithmetic
Pointer arithmetic involves performing operations on pointer variables. The most common
operations include:
1. Increment (++): Moves the pointer to the next memory location.
2. Decrement (--): Moves the pointer to the previous memory location.
3. Addition/Subtraction (+/-): Adjusts the pointer by a specified number of elements.
How Pointer Arithmetic Works
When a pointer is incremented or decremented, it moves by the size of the data type it points to
(e.g., sizeof(int) for an int pointer).
---
Example Program: Pointer Arithmetic
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("Initial pointer value:\n");
printf("Address: %p, Value: %d\n", ptr, *ptr);
ptr++;
printf("\nAfter incrementing pointer:\n");
printf("Address: %p, Value: %d\n", ptr, *ptr);
ptr--;
printf("\nAfter decrementing pointer:\n");
printf("Address: %p, Value: %d\n", ptr, *ptr);
ptr = ptr + 2;
printf("\nAfter adding offset 2:\n");
printf("Address: %p, Value: %d\n", ptr, *ptr);
ptr = ptr - 1;
printf("\nAfter subtracting offset 1:\n");
printf("Address: %p, Value: %d\n", ptr, *ptr);
return 0;
}