文档介绍:Part V
Arrays and Pointers
C++ By
23EXAMPLE
Introducing Arrays
This chapter discusses different types of arrays. You are already
familiar with character arrays, which are the only method for storing
character strings in the C++ language. A character array isn’t the
only kind of array you can use, however. There is an array for every
data type in C++. By learning how to process arrays, you greatly
improve the power and efficiency of your programs.
This chapter introduces
♦ Array basics of names, data types, and subscripts
♦ Initializing an array at declaration time
♦ Initializing an array during program execution
♦ Selecting elements from arrays
The sample programs in these next few chapters are the most
advanced that you have seen in this book. Arrays are not difficult to
use, but their power makes them well-suited to more advanced
programming.
473
Chapter 23 ♦ Introducing Arrays
Array Basics
An array is a list of Although you have seen arrays used as character strings, you
more than one still must have a review of arrays in general. An array is a list of more
variable having the
same name. than one variable having the same name. Not all lists of variables are
arrays. The following list of four variables, for example, does not
qualify as an array.
sales bonus_92 first_initial ctr
This is a list of variables (four of them), but it isn’t an array
because each variable has a different name. You might wonder how
more than one variable can have the same name; this seems to violate
the rules for variables. If two variables have the same name, how can
C++ determine which you are referring to when you use that name?
Array variables, or array elements, are differentiated by a
subscript, which is a number inside brackets. Suppose you want to
store a person’s name in a character array called name. You can do
this with
char name[] = “Ray Krebbs”;
or
char name[11] = “Ray Krebbs”;
Because C++ reserves an