Pointer Arithmetic in C
Introduction
In C Programming, Pointer arithmetic is an essential concept that allows us to perform arithmetic operations on pointers. It involves four basic operations: addition, subtraction, increment, and decrement. But unlike normal variables, pointers increment and decrement in steps of the size of the datatype that the pointer points to. This tutorial will guide you through the basics of pointer arithmetic in C.
Understanding Pointers
Before we delve into pointer arithmetic, let's quickly revise what pointers are.
A pointer is a variable whose value is the address of another variable. Here is how you can declare a pointer:
int *p; // 'p' is a pointer to an integer
In the above example, an integer pointer p
is declared. It means it can hold the address of an integer variable.
Pointer Arithmetic
Pointer arithmetic is performed in a different way than normal arithmetic. When we increment a pointer, it gets incremented by the size of the data type it points to. The same happens when we decrement a pointer, it gets decremented by the size of the data type it points to.
Addition
We can add an integer to a pointer, which advances the pointer by some number of elements. For instance, if p
is a pointer to an integer (which occupies 4 bytes), then p + 1
will advance p
by 4 bytes.
int *p;
int x = 10;
p = &x;
p = p + 1; // incrementing the pointer
Subtraction
We can subtract an integer from a pointer, which moves the pointer backward by some number of elements. Like addition, if p
is a pointer to an integer (which occupies 4 bytes), then p - 1
will move p
backward by 4 bytes.
int *p;
int x = 10;
p = &x;
p = p - 1; // decrementing the pointer
Increment
Incrementing a pointer means increasing the pointer value to the next memory location of its type. Here is how we can increment a pointer:
int *p;
int x = 10;
p = &x;
p++; // incrementing the pointer
Decrement
Decrementing a pointer means decreasing the pointer value to the previous memory location of its type. Here is how we can decrement a pointer:
int *p;
int x = 10;
p = &x;
p--; // decrementing the pointer
Conclusion
Understanding pointer arithmetic is crucial when dealing with arrays and dynamic memory allocation in C. It allows us to traverse through an array, allocate dynamic memory, and many more. Remember, when you perform arithmetic operations on pointers, it will increment or decrement considering the size of the data type it points to.
Keep practicing with different examples to get a good grasp of pointer arithmetic in C. Happy Coding!