C++ Primer For Java Programmers


Arrays

<< Dynamic Memory | Table of Contents | Arrays And Pointers >>
(:toc:)

An array is a structured type which provides a collection of data items, all of the same type, that can be accessed individually. In Java, arrays are dynamic objects containing a sequential collection of elements and a length field as illustrated below

In C++, an array is a sequential collection of elements but they can be either static or dynamic. That is, their size can be specified at compile-time or run-time. A few notes about arrays in C++

  • C++ arrays do not contain a length field. You must keep track of array sizes yourself.
  • An array can be created of any legal C++ data type, either built-in or user-defined.
  • Array elements are numbered starting at zero, the same as in Java.
  • Elements are referenced by subscript (gradeList[0]), the same as they are in Java.
  • No range checking is performed when accessing an array element. Thus, if you can refer to an element beyond the last allocated and no error occurs. It is up to you to stay within bounds.
  • There are no aggregate operations defined for C++ arrays which can be applied to the entire array.

Static Arrays

A static array is one in which the size is specified at compile-time. Thus, the size of the array must be a literal integer value or a value stored in a constant literal variable.

Creating a Static Array. To create a static array, the data type and the number of elements contained in the array are specified

(:source lang=cpp:)
int gradeList[ 5 ];

Note that the elements themselves are not initialized to any given value and will contain whatever value was previously in that location. Assuming values have been assigned to the array, the result of the above declaration appears as follows

Even though the array gradeList is static, there is a pointer variable associated with it which points to the first element in the list. A static array pointer, however, is constant and can not be modified once it has been created.

Array Size. Since C++ does not keep track of the size of an array, it is easy to go out of bounds. You should create constant variables to represent the size of any array you create. That way, the constant variable can be used later in the program when you need to refer to the array size.

(:source lang=cpp:)
const int NUM_GRADES = 5;

int main()
{
  int gradeList[ NUM_GRADES ];
          :
          :
  int i = 0;
  while( i < NUM_GRADES ) {
    printf( "%d\n", gradeList[ i ] );
    i++;
  }
}

Initializing Elements. A static array can be initialized when it is created using curly braces as in Java. Consider the following C++ examples

(:source lang=cpp:)
int valueList[] = { 5, 10, 15, 20, 25, 30, 35 };
int bigList[ 10 ] = { 1, 2, 3 };

The static array valueList is created containing 7 elements and initialized with the 7 supplied values. The static array bigList contains 10 elements but only the first 3 are initialized with the 3 values specified in the list.

In C++, you can initialize every element of a static array to a single value by including a single value within curly braces as in the following

(:source lang=cpp:)
int smallList[ 4 ] = { 0 };  

which results in

Dynamic Elements

In the example in the previous section, the static arrays contained static elements -- each element of the arrays were the same as a static variable of the given type. But arrays in C++ can also contain dynamic elements. That is, the elements are pointers to a given type. In the following example,

(:source lang=cpp:)
int * oreValues[ NUM_VALUES ] = { NULL };

we create a 5 element static array in which each element is a pointer to an int. The elements are set to the NULL pointer since we use the group initialization approach of a single value within curly braces. The result of this statement is illustrated below

(:note info:) This is the same as arrays of objects in Java where the array stores pointers to to objects and not the objects themselves. (:noteend:)

Filling In The Array. If an array stores pointers to data, then the elements can only be assigned a pointer or reference. Consider the following code segment

(:source lang=cpp:)
for( int i = 0; i < NUM_VALUES; i++ ) {
  moreValues[ i ] = new int;   // assign a dyanmic variable.
  *moreValues[ i ] = i;        // dereference the dynamic variable.
}

which produces the following

Dynamic Element Access. Since the elements of the array are pointers, we must use the dereferencing notation in order to access an individual element. The variable reference

(:source lang=cpp:)
moreValues[ 2 ]

refers to the third element of the array which is a pointer to an int. To access the dyanmic int variable pointed to by that element which contains the value 2, we must dereference it using

(:source lang=cpp:)
*moreValues[ 2 ]

Array Parameters

When an array is passed to a function, only the reference or pointer is passed and not the entire array. The C++ notation for passing an array uses empty brackets following the variable name (see the Arrays And Pointers section for an alternate method of passing arrays as parameters).

(:source lang=cpp:)
void printGrades( int theGrades[], int num )
{
  for( int i = 0; i < num; i++ )
    printf( "%d\n", theGrades[ i ] );
}

To pass the array to the function, only the array name is specified since it is an int pointer and both function prototypes indicate an int pointer argument.

(:source lang=cpp:)
printGrades( gradeList, NUM_GRADES );

The result of passing an array to a function is the assignment of the array or pointer variable to a local variable within the function. Remember that pointer asignment can only occur between pointers of the same type.

(:note info:) Since a pointer parameter can be intended as either a reference to a single variable or to an array, you must be told what is required by such functions. (:noteend:)

Arrays of Structs

(:source lang=cpp:)
struct StudentRecord {
  int idNum;
  int classYear;
  float gpa;
};

const int MAX_RECORDS = 100;

StudentRecord studentList[ MAX_RECORDS ];
int numRecords = 0;

float computeAvgGPA( StudentRecord theList[], int numRecs )
{
  int sum = 0;
  for( int i = 0; i < numRecs; i++ ) 
    sum = sum + theList[ i ].gpa;
  return float( sum ) / numRecs;  
}


<< Dynamic Memory | Table of Contents | Arrays And Pointers >>

Print - Changes - Search
Last modified: April 30, 2007, at 10:45 PM.