Tuesday 8 November 2011

When you add a value to a pointer, what is really added? in C programming

When you add a value to a pointer, what is really added?

 If you think only in terms of raw addresses, what’s “really” added is the value times the size of the thing being
pointed to...and you’re missing the point of how C pointers work. When you add an integer and a pointer,
the sum points that many elements away, not just that many bytes away.

Look at the end of Listing VII.7. When you add 8 to & array[0], you don’t get something eight bytes away.
You get & array[8], which is eight elements away.

Think about the street-address analogy presented in this chapter’s introduction. You live on the evennumbered
side of Oak Street, at number 744. There are no gaps in the even numbers. The “size of a house”
is 2. If someone wants to know the address of the place three doors up from you, he multiplies the size (2)
times 3, and thus adds 6; the address is 750. The house one door down is 744 + (–1)*2, or 742.
Street-address arithmetic works only within a given block; pointer arithmetic works only within a given array.
If you try to calculate the address 400 blocks south of you, you’ll get –56 Oak Street; fine, but that doesn’t
mean anything. If your program uses a meaningless address, it’ll probably blow up.

Cross Reference:

VII.7: Can you subtract pointers from each other? Why would you?
VII.12: Can you add pointers together? Why would you?
VII.27: Can math operations be performed on a void pointer?

No comments:

Post a Comment