dlowrie290 dlowrie290 - 3 months ago 25
C++ Question

c/c++ ptr arithmetic with number not divisible by 4

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
as does
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[10];
int *ptr = &arr[0];

the expression ptr + 3 yields &arr[3]. That will be 3*4 bytes after the address of ptr[0] if and only if sizeof (int) == 4. If arr is an array of char, and ptr is a char*, then ptr + 3 is still &arr[3], but it's only 3 bytes after &arr[0].

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.