C++ array

From Just Solve the File Format Problem
(Difference between revisions)
Jump to: navigation, search
(Created page with "{{FormatInfo | name = C++ array | formattype = electronic | subcat = Data types | subcat2 = C++ data types | subcat3 = | subcat4 = ...")
 
(passing array)
Line 36: Line 36:
 
==Arrays and pointers==
 
==Arrays and pointers==
 
: See [[C%2B%2B_pointer#Pointer_to_an_array|C++ pointer]]
 
: See [[C%2B%2B_pointer#Pointer_to_an_array|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:
 +
 +
<pre>void foo(int[]);</pre>
 +
 +
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.
  
 
==See also==
 
==See also==
 
* [[std::array]] C++ array template class
 
* [[std::array]] C++ array template class

Revision as of 14:52, 13 May 2015

File Format
Name C++ array
Ontology
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.

Contents

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.

See also

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox