When we subtract a pointer from another pointer the difference is not equal to how many bytes they are apart but equal to how many integers (if pointing to integers) they are apart. Why so?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Say you have an array of 10 integers:
Then you take a pointer to intArray:
Then you increment
p
:What you would expect, because
p
starts atintArray[0]
, is for the incremented value ofp
to beintArray[1]
. That's why pointer arithmetic works like that. See the code here.This is consistent with the way pointer addition behaves. It means that
p1 + (p2 - p1) == p2
*.Pointer addition (adding an integer to a pointer) behaves in a similar way:
p1 + 1
gives you the address of the next item in the array, rather than the next byte in the array - which would be a fairly useless and unsafe thing to do.C could have been designed so that pointers are added and subtracted the same way as integers, but it would have meant:
p2 = p1 + n * sizeof(*p1)
instead ofp2 = p1 + n
n = (p2 - p1) / sizeof(*p1)
instead ofn = p2 - p1
This would result in code that is longer, harder to read, and less safe.
*: assuming that the difference between p1 and p2 is an exact multiple of the type they point to. If they are in the same array of memory, this will be true. If they are not, then it doesn't much sense doing pointer arithmetic on them.
So that the answer is the same even on platforms where integers are different lengths.
@fahad Pointer arithmetic goes by the size of the datatype it points.So when ur pointer is of type int you should expect pointer arithmetic in the size of int(4 bytes).Likewise for a char pointer all operations on the pointer will be in terms of 1 byte.
The idea is that you're pointing to blocks of memory
If you have
int* p = &(array[5])
then*p
will be 14. Goingp=p-3
would make*p
be 17.So if you have
int* p = &(array[5])
andint *q = &(array[3])
, thenp-q
should be 2, because the pointers are point to memory that are 2 blocks apart.When dealing with raw memory (arrays, lists, maps, etc) draw lots of boxes! It really helps!
"When you subtract two pointers, as long as they point into the same array, the result is the number of elements separating them"
Check for more here.