I am needing to learn about ptr arithemtic for a class, but I am confused by something.
I understand that the ptr incrementation is basically multiples of 4, so if...
ptr++ basically = 4bytes
ptr = 1
my question is what if you want to make the ptr equal something that isn't divisible by 4, like say 2606.
in the code that I need to modify we see...
ptr = ptr + 652;
this would equal 2608
if I change the code to...
ptr = ptr + 651
then it equals 2604
what do I need to do to modify this to make the ptr equal 2606?
Thanks in advance.
No, pointer arithmetic is not generally in multiples of 4. It is in multiples of the size of the pointed-to type -- and it's valid only when both the starting value and the resulting value point to elements of the same array object, or just past the end of it.
For example, given:
int arr; int *ptr = &arr;
ptr + 3 yields
&arr. That will be 3*4 bytes after the address of
ptr if and only if
sizeof (int) == 4. If
arr is an array of
ptr is a
ptr + 3 is still
&arr, but it's only 3 bytes after
Any operation that tries to add a fraction of the element size to a pointer is invalid. You can try to do it by casting the pointer to
char*, performing the addition, and then casting back, but the result will be misaligned, and the behavior is undefined. Don't do that.