Move by elements, not guessed byte counts
Adding one to an int pointer advances to the next int element, not necessarily the next machine byte. Pointer arithmetic is defined within an array and at its one-past position. The one-past pointer may be used as a boundary but must not be dereferenced.
Traverse an array safely
#include
#include
int main(void) {
int values[] = {10, 20, 30, 40};
int *begin = values;
int *end = values + 4;
for (int *p = begin; p != end; ++p) {
printf("%d ", *p);
}
printf("\ncount=%td\n", end - begin);
return 0;
} Expected output is 10 20 30 40, then count=4. The pointer difference has type ptrdiff_t and uses %td. Subtracting pointers is meaningful only under the language's same-array rules and when the result can be represented.
Relationship to subscripting
For a valid index, values[i] means *(values + i). In many expressions the array name converts to a pointer to its first element. That does not make an array a pointer object: an array has its own storage and cannot be reassigned, while a pointer variable can hold a different address. sizeof applied to an array is a notable context where the whole array is measured.
Bounds remain your responsibility
Do not form a pointer two positions beyond the end and later move it back; merely forming an out-of-bounds pointer can already violate the rules. Do not order unrelated object pointers to decide which object is “earlier”. Keep iteration boundaries tied to a single array.
Read tricky expressions deliberately
*p++ is grouped as *(p++): it accesses the current element and advances p. (*p)++ increments the element instead. In teaching and maintenance code, value = *p; ++p; can be clearer. Multiple side effects in one expression are a frequent source of mistakes.
Exercises with checks
- Print the array in reverse without decrementing before begin: start from end, then decrement before dereferencing while p is not begin.
- Find the sum with pointer traversal. Expected sum: 100.
- Explain why
*endis invalid even though end is a permitted boundary pointer. - Inside a function taking
const int *values, size_t count, traverse exactly count elements. Do not try to recover count with sizeof on the parameter.
हिन्दी संकेत: pointer की चाल उसके pointed-to type के element के हिसाब से होती है। One-past address सीमा है, पढ़ने योग्य element नहीं।