Illegal pointer arithmetic operations
What you'll learn: You will learn which mathematical operations are forbidden with pointers to avoid memory errors and compiler crashes.
Up to this point, you have seen that pointers act a lot like integers because they store memory addresses. You can add to them to move forward through an array or subtract to move backward. However, pointers are not just numbers; they are specific "GPS coordinates" for your computer’s memory. Because of this, there are strict rules about what you cannot do with them.
You cannot add two pointers
Imagine you and a friend are standing on a long sidewalk. You are at tile number 100, and your friend is at tile number 102. If you add your positions together (100 + 102), you get 202. What does 202 represent? Nothing. It’s just a random spot further down the street that has no relationship to where you were standing.
In C, adding two pointers (like ptr1 + ptr2) is illegal. The compiler will stop you because the resulting address is logically meaningless and could point to a restricted area of memory, causing your program to crash.
You cannot multiply or divide pointers
If adding pointers is meaningless, multiplying them is even worse. There is no scenario in programming where squaring a memory address or dividing one address by another helps you access data. These operations are strictly forbidden. Similarly, you cannot use the modulo operator (%) on pointers.
You cannot perform bitwise operations
Pointers do not allow bitwise logic like "AND," "OR," or "Left Shift." While these are common for manipulating raw binary numbers, applying them to a pointer would scramble the memory address, making it point to a "garbage" location.
Examples of illegal code
Here is what these errors look like in practice. If you try to compile this, the compiler will throw an error.
#include <stdio.h>
int main() {
int nums[] = {10, 20, 30};
int *p1 = &nums[0];
int *p2 = &nums[1];
// ILLEGAL: You cannot add two addresses
// int *result = p1 + p2;
// ILLEGAL: You cannot multiply addresses
// int *result = p1 * p2;
// ILLEGAL: You cannot use bitwise logic
// int *result = p1 << 1;
return 0;
}
Key takeaway
Pointers only support addition/subtraction with integers and subtraction between two pointers; multiplication, division, and adding two pointers together are illegal.