Wednesday, August 1, 2012

C++ Essentials

C++ Essentials

Sharam Hekmat

Pointer Arithmetic

In C++ one can add an integer quantity to or subtract an integer quantity from a
pointer. This is frequently used by programmers and is called pointer arithmetic.
Pointer arithmetic is not the same as integer arithmetic, because the outcome
depends on the size of the object pointed to. For example, suppose that an int is
represented by 4 bytes. Now, given
char *str = "HELLO";
int  nums[] = {10, 20, 30, 40};
int  *ptr = &nums[0]; // pointer to first element
str++ advances str by one char (i.e., one byte) so that it points to the second
character of "HELLO", whereas ptr++ advances ptr by one int (i.e., four bytes)
so that it points to the second element of  nums. Figure 5.8 illustrates this
diagrammatically.



No comments:

Post a Comment