C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

25. Arrays and Pointers


In This Chapter


  • Understanding that array names are pointers

  • Getting down in the list

  • Working with characters and pointers

  • Being careful with string lengths

  • Creating arrays of pointers


This chapter teaches how C’s array and pointer variables share a lot of principles. As a matter of
fact, an array is a special kind of pointer. Because of their similarities, you can use pointer notation to
get to array values, and you can use array notation to get to pointed-at values.


Perhaps the most important reason to learn how arrays and pointers overlap is for character string
handling. By combining pointer notation (using the dereferencing operation) and array notation (using
subscripts), you can store lists of character strings and reference them as easily as you reference array
values of other data types.


Also, after you master the heap—a special place in memory that the next chapter introduces you to—
you’ll see that pointers are the only way to get to heap memory, where you put data values.


Array Names Are Pointers


An array name is nothing more than a pointer to the first element in that array. The array name is not
exactly a pointer variable, though. Array names are known as pointer constants. The following
statement defines an integer array and initializes it:


Click here to view code image


int vals[5] = {10, 20, 30, 40, 50};

You can reference the array by subscript notation. That much you know already. However, C does
more than just attach subscripts to the values in memory. C sets up a pointer to the array and names
that point to vals. You can never change the contents of vals; it is like a fixed pointer variable
whose address C locks in. Figure 25.1 shows you what C really does when you define and initialize
vals.

Free download pdf