Why use an Index when you can touch the Memory? π
Day 2/30: Pointer Arithmetic.
Most tutorials teach you to loop through arrays using i (the index). But in Systems Programming, we often manipulate the address directly.
The Magic: When you write ptr++ in C, the compiler is smart. It doesn't just add "1" to the address. It adds sizeof(int) (usually 4 bytes).
If ptr was a char, it would add 1 byte. If ptr was a struct, it would jump the size of the whole struct.
This snippet allows us to iterate through data purely by comparing memory addresses, which is more direct and cleaner in low-level drivers.
The Code
Here is the C code for Day 2:
// Day 2: Traversing Memory without an Index
void iterate_with_pointers(const int *ptr, int size) {
// We don't need 'i' or 'array[i]'
// We just look at the end address
int *end = ptr + size;
while (ptr < end) {
// Dereference the current address to get value
printf("Value: %d\n", *ptr);
// Move the pointer to the next integer block
// (Jumps 4 bytes automatically)
ptr++;
}
}
Top comments (1)
If
ptris a pointer toconst, thenendshould likewise be a pointer toconst.