다음을 통해 공유


Using Arrays (C++)

Individual elements of arrays are accessed using the array subscript operator ([ ]). If a singly dimensioned array is used in an expression with no subscript, the array name evaluates to a pointer to the first element in the array. For example:

// using_arrays.cpp
int main() {
   char chArray[10];
   char *pch = chArray;   // Pointer to first element.
   char   ch = chArray[0];   // Value of first element.
   ch = chArray[3];   // Value of fourth element.
}

When using multidimensional arrays, various combinations are acceptable in expressions. The following example illustrates this:

// using_arrays_2.cpp
// compile with: /EHsc /W1
#include <iostream>
using namespace std;
int main() {
   double multi[4][4][3];   // Declare the array.
   double (*p2multi)[3];
   double (*p1multi);

   cout << multi[3][2][2] << "\n";   // C4700 Use three subscripts.
   p2multi = multi[3];               // Make p2multi point to
                                     // fourth "plane" of multi.
   p1multi = multi[3][2];            // Make p1multi point to
                                     // fourth plane, third row
                                     // of multi.
}

In the preceding code, multi is a three-dimensional array of type double. The p2multi pointer points to an array of type double of size three. The array is used with one, two, and three subscripts in this example. Although it is more common to specify all the subscripts, as in the cout statement, it is sometimes useful to select a specific subset of array elements as shown in the succeeding statements.

See Also

Reference

Arrays (C++)