Pointers and Arrays


There is a close-knit relationship between a pointer and an array. The array name is like a pointer variable in that the array name by itself references the address of the first element of the array. Confused? We ll give you an example (see Figure 3-7) to show how this works.

click to expand
Figure 3-7: Use the array name as a pointer to the first array element.

Java doesn t permit a programmer to use pointers, so we use C++ code in Figure 3-7. The example begins by declaring an array of characters called letters that consists of 2 elements. Also declared is a character pointer called ptLetters . (You learned about pointers in Chapter 2.)

Next, the character A is assigned to the first element of the array. The address of the first array element is then assigned to the pointer variable. Figure 3-8 gives you a glimpse of memory once the address of the first array element is assigned to the pointer.

click to expand
Figure 3-8: Memory allocation after the pointer is assigned the address of the first array element

Figure 3-7 displays the letter A twice. The first time is by using the name of the array as a pointer. Only the name of the array is used ”the square brackets and index are not. The A is displayed the second time by using the pointer. Using the asterisk dereferences both the array name and the pointer. (You learned about dereferencing in Chapter 2.)

You might be wondering why you d use the array name as a pointer to the first element of the array. Programmers do this to use pointer arithmetic (see the Pointer Arithmetic section of Chapter 2) to access each array element without having to reference an array index.




Data Structures Demystified
Data Structures Demystified (Demystified)
ISBN: 0072253592
EAN: 2147483647
Year: 2006
Pages: 90

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net