Pointer Arithmetic
Adding n to a pointer moves it by n elements, not n bytes.
Intermediate
int data[4] = {10, 20, 30, 40};
int *p = data;
*(p + 2); // 30 — same as data[2]
p++; // now points to data[1]
If int is 4 bytes, p + 1 advances the address by 4. Subtracting two pointers into the same array gives the number of elements between them. Arithmetic outside the array (except one past the end) is undefined behaviour.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.