2. Pointer Arithmetic #
Created Saturday 21 December 2019
Addition and subtraction of integers is allowed on pointer variables(except null and void pointers). Other arithmetic operations such as multiplication and division are not allowed.
Reason: As we don’t know the memory they reference and the jump, respectively, void* are increased by 1 in some compilers, but this is not a standard, it is done only if the -pedantic
flag is used.
- When we do +2 for a pointer, we actually do start_address + 2*sizeof(data_type) . Similarly for subtraction.
- Variables declared together need not be contiguos. Memory is actually allocated as per availability.
- Array elements are always contiguos - definition of array.
- Each ±1 adds/subtracts by the sizeof(data_type).
- Everthing in pointer-land is about offsets, not about the addresses themselves.
Note:
- Pointers may be compared by using relational operators, such as ==, <, and >. This meaningful only if p1 and p2 are related to each other, such as elements of the same array.