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

(Romina) #1
FIGURE 25.2 The movies array contains pointers to strings.

See, even though there is no such thing as a string array in C (because there are no string variables),
storing character pointers in movies makes the program act as though movies is a string array.


The program then loops through the nine movies in the array and asks the user whether he or she saw
each one. If the answer is Y (or y after it is converted with the toupper() function), the program
goes on to ask for an integer rating of 1 to 10. It also increments a counter (ctr) so the program will
eventually know how many movies were seen. If the answer is N (or any character other than Y or y),
the rating of -1 is assigned to that movie, so it will fall to the bottom during the movie sort.


After the movies are all rated, a bubble sort is used to rate the movies best to worst. Isn’t it nice to
know that you can use your sort routine on string arrays? The sorted array is now ready to be printed.
However, the for loop iterates only ctr times, meaning that it will not print the names of movies
you didn’t see.


The Absolute Minimum
The goal of this chapter was to get you thinking about the similarities between arrays
and pointers. An array name is really just a pointer that points to the first element in the
array. Unlike pointer variables, an array name can’t change. This is the primary reason
an array name can’t appear on the left side of an equals sign.
Using pointers allows more flexibility than arrays. You can directly assign a string
literal to a character pointer variable, whereas you must use the strcpy() function
to assign strings to arrays. You’ll see many uses for pointer variables throughout your
C programming career. Key concepts from this chapter include:


  • Use character pointers if you want to assign string literals directly.

  • Use either array subscript notation or pointer dereferencing to access array and
    pointer values.

  • Don’t use a built-in function to fill a character pointer’s location unless that
    character pointer was originally set up to point to a long string.

Free download pdf