Arrays

An array holds a collection of objects of some type. Arrays are fixed size; once an array is created, new elements cannot be added. Arrays are data structures that are similar to library vectors but are built into the language. Like a vector, an array is a container of objects of a single data type. The individual objects are not named; rather, each one is accessed by its position in the array.

An array is a compound type that consists of a type specifier, an identifier, and a dimension.

Example
Initializing an array

// both buf_size and max_files are const
          const unsigned buf_size = 512, max_files = 20;
          int staff_size = 27;            // nonconst
          const unsigned sz = get_size();  // const value not known until run time
          char input_buffer[buf_size];     // ok: const variable
          string fileTable[max_files + 1]; // ok: constant expression
          double salaries[staff_size];     // error: non const variable
          int test_scores[get_size()];     // error: non const expression
          int vals[sz];                    // error: size not known until run time

Example
Array elements may be accessed using the subscript operator

int main()
          {
              const size_t array_size = 10;
              int ia[array_size]; // 10 ints, elements are uninitialized
 
              // loop through array, assigning value of its index to each element
              for (size_t ix = 0; ix != array_size; ++ix)
                    ia[ix] = ix;
              return 0;
          }

Example
Using a similar loop, we can copy one array into another.

int main()
          {
              const size_t array_size = 10;
              int ia[array_size]; // 10 ints, elements are uninitialized
 
              // loop through array, assigning value of its index to each element
              for (size_t ix = 0; ix != array_size; ++ix)
                    ia[ix] = ix;
              return 0;
          }
page_revision: 1, last_edited: 1196852726|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.