Submitted by Anonymous (not verified) on Sun, 03/10/2013 - 20:15

Question and Answer

    Q Why do you need pointer arithmetic?

    A The beauty of using pointers is that you can move pointers around to get access to valid data that is saved in those memory locations referenced by the pointers. To do so, you can perform the pointer arithmetic to add (or subtract) an integer to (or from) a pointer. For example, if a character pointer, ptr_str, holds the start address of a character string, the ptr_str+1 expression means to move to the next memory location that contains the second character in the string.

    Q How does the compiler determine the scalar size of a pointer?

    A The compiler determines the scalar size of a pointer by its data type specified in the declaration. When an integer is added to or subtracted from a pointer, the actual value the compiler uses is the multiplication of the integer and the size of the pointer type. For instance, given an int pointer ptr_int, the ptr_int + 1 expression is interpreted by the compiler as ptr_int + 1 * sizeof(int). If the size of the int type is 2 bytes, then the ptr_int + 1 expression really means to move 2 bytes higher from the memory location referenced by the ptr_int pointer.

    Q How do you get access to an element in an array by using a pointer?

    A For a one-dimensional array, you can assign the start address of an array to a pointer of the same type, and then move the pointer to the memory location that contains the value of an element in which you're interested. Then you dereference the pointer to obtain the value of the element. For multidimensional arrays, the method is similar, but you have to think about the other dimensions at the same time. (See the example shown in Listing 16.6.)

    Q Why do you need to use arrays of pointers?

    A In many cases, it's helpful to use arrays of pointers. For instance, it's convenient to use an array of pointers to point to a set of character strings so that you can access any one of the strings referenced by a corresponding pointer in the array.
 

Related Items

Using the Precision Specifier

Using the Precision Specifier

Aligning Output

Aligning Output
As you might have noticed in the previous section, all output is right-justified. In other words, by default, all output is placed on the right edge of the field, as long as the field width is longer than the width of the output.

 

Adding the Minimum Field Width

Adding the Minimum Field Width

Converting to Hex Numbers

Converting to Hex Numbers

Revisiting the printf() Function

Revisiting the printf() Function

The printf() function is the first C library function you used in this book to print out messages on the screen. printf() is a very important function in C, so it's worth it to spend more time on it.