C++ array

From Just Solve the File Format Problem
Jump to: navigation, search
File Format
Name C++ array
Released 1983

C++ array is a way to store a series of data of the same type and purpose, the data then can be accessed by the name of the array and index within it. C++ array index always begins with 0 and goes to the value 1 less than the size of an array.

Index is written within square brackets. This way of indexing data has become so associated with arrays, that many people expect that only arrays can do that. This is not the case, since it is possible to define operator[] for any type.

C++ does not provide safety for dereferencing array elements. It becomes the job of the programmer to track and check that the element really exists within a specific array before trying to do any operations with it. Failing to do so will lead to undefined behaviour.


Dynamic vs static arrays

Static arrays must have a known declaration at compile time, meaning that it is not possible to have a scenario where the application makes the decision about the size of an array during its operation. Static arrays are normally placed inside the stack of the program.

Dynamic arrays are placed within the heap and can have the size that it determined at the run time.

Neither of these, however, can have the size, that changes after it has been declared.

Arrays and pointers

See C++ pointer

Passing array as a parameter to a function

The correct way to write a declaration for a function, that expects an array would be to add square brackets to the data type:

void foo(int[]);

It should be noted, that there is no way to pass an array by value in C++ (without manually copying an array into another one). The default behaviour is to pass it by reference.

Placement of data within the array

Data is placed within the array at equal intervals. Usually these intervals are equal to the size of the data type of individual cell. The end of the array may have some padding with unused memory.

Matrices and jagged arrays

There is no way to declare a static jagged array in C++, thus any multidimentional array is a multidimentional matrix. In order to make a jagged array one must use an array of pointers and create each subarray separately.

int a[5][3];    // this is a matrix 5 by 3

int * a[5];      // this will become a jagged array
a[0] = new int[1];
a[1] = new int[3];
a[2] = new int[4];
a[3] = new int[2];
a[4] = new int[8];

See also

Personal tools