Size Of C++ Array Assignment

As others have mentioned, is generally the way to go. The reason is that vector is very well understood, it's standardized across compilers and platforms, and above all it shields the programmer from the difficulties of manually managing memory. Moreover, vector elements are required to be allocated sequentially (i.e., vector elements A, B, C will appear in continuous memory in the same order as they were pushed into the vector). This should make the vector as cache-friendly as a regular dynamically allocated array.

While the same end result could definitely be accomplished by declaring a pointer to int and manually managing the memory, that would mean extra work:

  1. Every time you need more memory, you must manually allocate it
  2. You must be very careful to delete any previously allocated memory before assigning a new value to the pointer, lest you'll be stuck with huge memory leaks
  3. Unlike , this approach is not RAII-friendly. Consider the following example:

It looks safe and sound. But it isn't. What if, upon attempting to allocate 10 bytes for "somethingElse", the system runs out of memory? An exception of type will be thrown, which will start unwinding the stack looking for an exception handler, skipping the delete statements at the end of the function. You have a memory leak. That is but one of many reasons to avoid manually managing memory in C++. To remedy this (if you really, really want to), the Boost library provides a bunch of nice RAII wrappers, such as scoped_array and scoped_ptr.


An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

That means that, for example, we can store 5 values of type in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, for example, with a unique identifier.

For example, an array to contain 5 integer values of type called could be represented like this:

where each blank panel represents an element of the array, that in this case are integer values of type . These elements are numbered from to since in arrays the first index is always , independently of its length.

Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:

where is a valid type (like , ...), is a valid identifier and the field (which is always enclosed in square brackets ), specifies how many of these elements the array has to contain.

Therefore, in order to declare an array called as the one shown in the above diagram it is as simple as:

NOTE: The field within brackets which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.

Initializing arrays.

When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros.

In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces . For example:

This declaration would have created an array like this:

The amount of values between braces must not be larger than the number of elements that we declare for the array between square brackets . For example, in the example of array we have declared that it has 5 elements and in the list of initial values within braces we have specified 5 values, one for each element.

When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty . In this case, the compiler will assume a size for the array that matches the number of values included between braces :

After this declaration, array would be 5 ints long, since we have provided 5 initialization values.

Accessing the values of an array.

In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:

Following the previous examples in which had 5 elements and each of those elements was of type , the name which we can use to refer to each element is the following:

For example, to store the value in the third element of , we could write the following statement:

and, for example, to pass the value of the third element of to a variable called , we could write:

Therefore, the expression is for all purposes like a variable of type .

Notice that the third element of is specified , since the first one is , the second one is , and therefore, the third one is . By this same reason, its last element is . Therefore, if we write billy[5], we would be accessing the sixth element of and therefore exceeding the size of the array.

In C++ it is syntactically correct to exceed the valid range of indices for an array. This can create problems, since accessing out-of-range elements do not cause compilation errors but can cause runtime errors. The reason why this is allowed will be seen further ahead when we begin to use pointers.

At this point it is important to be able to clearly distinguish between the two uses that brackets have related to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of brackets with arrays.

If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it never precedes an access.

Some other valid operations with arrays:

Multidimensional arrays

Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type.

represents a bidimensional array of 3 per 5 elements of type . The way to declare this array in C++ would be:

and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be:

(remember that array indices always begin by zero).

Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many indices as needed. But be careful! The amount of memory needed for an array rapidly increases with each dimension. For example:

declares an array with a element for each second in a century, that is more than 3 billion chars. So this declaration would consume more than 3 gigabytes of memory!

Multidimensional arrays are just an abstraction for programmers, since we can obtain the same results with a simple array just by putting a factor between its indices:

With the only difference that with multidimensional arrays the compiler remembers the depth of each imaginary dimension for us. Take as example these two pieces of code, with both exactly the same result. One uses a bidimensional array and the other one uses a simple array:

multidimensional arraypseudo-multidimensional array
#define WIDTH 5 #define HEIGHT 3 int jimmy [HEIGHT][WIDTH]; int n,m; int main () { for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n][m]=(n+1)*(m+1); } return 0; } #define WIDTH 5 #define HEIGHT 3 int jimmy [HEIGHT * WIDTH]; int n,m; int main () { for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n*WIDTH+m]=(n+1)*(m+1); } return 0; }

None of the two source codes above produce any output on the screen, but both assign values to the memory block called jimmy in the following way:

We have used "defined constants" () to simplify possible future modifications of the program. For example, in case that we decided to enlarge the array to a height of 4 instead of 3 it could be done simply by changing the line:


with no need to make any other modifications to the program.

Arrays as parameters

At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation.

In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array, an identifier and a pair of void brackets . For example, the following function:

accepts a parameter of type "array of " called . In order to pass to this function an array declared as:

it would be enough to write a call like this:

Here you have a complete example:

As you can see, the first parameter () accepts any array whose elements are of type , whatever its length. For that reason we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter. This allows the loop that prints out the array to know the range to iterate in the passed array without going out of range.

In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is:

for example, a function with a multidimensional array as argument could be:

Notice that the first brackets are left empty while the following ones specify sizes for their respective dimensions. This is necessary in order for the compiler to be able to determine the depth of each additional dimension.

Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors for novice programmers. I recommend the reading of the chapter about Pointers for a better understanding on how arrays operate.

0 Thoughts to “Size Of C++ Array Assignment

Leave a comment

L'indirizzo email non verrĂ  pubblicato. I campi obbligatori sono contrassegnati *