Home

Introduction to Arrays

 

Fundamentals of Arrays

 

Introduction

In some programs, you may need to represent a list of items that share some characteristics. You can declare as many variables as necessary to represent such items. Here is an example of 5 numbers declared in a program:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;
	
int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int number1 = 266;
    int number1 = -4683;
    int number1 = -364;
    int number1 = 1450;
    int number1 = 8;

    Console::WriteLine();
    return 0;
}

If you want to use a group of objects that are of the same kind, C++ allows you to identify them as one variable. An array is a group of variables that shared the same characteristics.

Author Note Arrays in Managed C++ are a little different than those traditionally used in C++ because the Microsoft .NET Framework introduced a new way of declaring and using arrays, which also has to do with inherited classes. Because this can be a long and arduous subject, we will use arrays only as they are used and implemented in managed classes.
 

Array Declaration 

An array is a group of values of the same kind or the same data type. Because the items are considered in a group, they are declared as one variable but the declaration must indicate that the variable represents various items. The items that are part of the group are also referred to as members of the array. To declare an array, you must give it a name.

In C++, the formula to declare an array is

DataType ArrayName[Dimension];

With this formula, an array would be declared as a value type. C++' arrays can be declared either on the stack as in the above formula or on the heap. Managed C++ formally introduces the idea of declaring an array on the heap. Based on this, (most) arrays in Managed C++ are referred to as managed arrays. In this case, the formula to declare a managed array is:

DataType ArrayName[] = new DataType[Dimension];

Another equivalent formula is:

DataType ArrayName __gc[] = new DataType __gc[Dimension];

Therefore, the declaration of a managed array starts by specifying a data type, the DataType in our syntax. This indicates the kind of values shared by the members of the array. It also specify the amount of memory space that each member of the array will need to store its value. Like any other variable, an array must have a name, which is the ArrayName in our syntax. The name of the array must be followed by an opening and a closing square brackets "[]". To indicate that you are declaring a managed array, you must assign the same data type as a managed type, using the new keyword. Once again, the data type must be followed by square brackets. This time, inside of the square brackets, you must type the number of items that the array is made of; that is the Dimension in our syntax.

To create a managed array, the data type can be a normal C/C++ data type such as int, double, or .NET value type such as Int32, Double, etc. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double Number[] = new Double[5];

    Console::WriteLine(S"");
    return 0;
}

To re-enforce the idea of declaring a managed array, you can optionally type the __gc keyword to the left of the square brackets. You can type it either on only one side of the assignment operator or on both sides. Therefore, the following declarations are equivalents:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;
	
int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double Number1[]      = new Double[5];
    Double Number2 __gc[] = new Double[5];
    Double Number3[]      = new Double __gc[5];
    Double Number4 __gc[] = new Double __gc[5];

    Console::WriteLine();
    return 0;
}

When declaring a managed array, you must use the new operator to indicate to the compiler that the variable would be declared on the heap. Because the new operator is explicit enough, you can omit the __gc keyword. Also, you don't have to perform the whole declaration at the same time but you must have requested that memory be allocated to the array before it can be used. Based on this, you can first declare the variable with the left part of the assignment operator. Then, when you are ready, you can allocate memory to the variable and specify the number of members of the array. When doing this, type the name of the variable without the square brackets and type the right side of our syntax. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;
	
int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double number[];
    // You can't yet use the array

    Console::WriteLine(S"The Wonderful World of Managed C++!");

    number = __gc new Double[5];
    // Now the array is ready

    Console::WriteLine();
    return 0;
}

We mentioned that, when declaring the array, you should specify the number of members of the array with the Dimension in our syntax. After declaring the array, if you want, you can reduce or increase the number of items by simply performing a new assignment to the variable and indicating the new desired Dimension. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;
	
int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double number[];
    // You can't yet use the array

    Console::WriteLine(S"The Wonderful World of Managed C++!");

    number = __gc new Double[5];
    // Now the array is ready

    // The new dimension of the array
    number = new Double[8];

    Console::WriteLine();
    return 0;
}

Initializing an Array

When declaring an array, before using it, we saw that you must specify the number of members of the array. This declaration allocates an amount of memory space to the variable. The first member of the array takes a portion of this space. The second member of the array occupies memory next to it:

Array Variable
 
    Member1 Member2 Member3 Member4 Member5  

Each member of the array can be accessed using its position. The position is also referred to as an index. The members of an array are arranged starting at index 0, followed by index 1, then index 2, etc. This system of counting is referred to as "zero-based" because the counting starts at 0. To locate a member, type the name of the variable followed by an opening and a closing square brackets. Inside the bracket, type the zero-based index of the desired member. After locating the desired member of the array, you can assign it a value, exactly as you would any regular variable. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double number[] = __gc new Double[5];

    number[0] = 643.18;
    number[1] = 9.64;
    number[2] = 48.05;
    number[3] = 14.26;
    number[4] = 62.55;

    Console::WriteLine(S"");
    return 0;
}

In the same way, you can retrieve the value of a member of an array based on its index. Such a value can be displayed to the user as follows:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double number[] = __gc new Double[5];

    number[0] = 643.18;
    number[1] = 9.64;
    number[2] = 48.05;
    number[3] = 14.26;
    number[4] = 62.55;

    Console::WriteLine(S"Value 1: {0}", __box(number[0]));
    Console::WriteLine(S"Value 2: {0}", __box(number[1]));
    Console::WriteLine(S"Value 3: {0}", __box(number[2]));
    Console::WriteLine(S"Value 4: {0}", __box(number[3]));
    Console::WriteLine(S"Value 5: {0}", __box(number[4]));

    number = new Double[8];

    Console::WriteLine(S"");
    return 0;
}

This would produce:

Value 1: 643.18
Value 2: 9.64
Value 3: 48.05
Value 4: 14.26
Value 5: 62.55

Press any key to continue

When it comes to initializing a managed array, you don't have to access each member of the array and initialize them individually. That technique is used if you don't yet have the values of the items at the time you are declaring the array. If you know the values of the members of the managed array at the time you are declaring its variable, you can declare and initialize the whole array at the same time. The formula you would use is:

DataType VariableName __gc[] = { Values Separated By Commas };

This formula is almost the same used in C/C++ with one difference. If you omit the __gc keyword, the array would be a regular one as used in C/C++. The alternative is to type the __gc keyword to the left of the square brackets. If you do this, two features would automatically be applied to your array. First, the array would be garbage collected, that is, cleaned up by the garbage collector; therefore becoming a managed array. Second, the array becomes automatically derived from the .NET's Array class, which gives it access to the properties and methods of that class.

If you use the formula we used earlier with the number variable, the data type must be a .NET value type such as Int32, Double, Single, etc. If you use the above formula to declare and initialize your array, the data type can be a regular C/C++ type (such as int, long, or double) or a .NET value type (such as Int32 or Double). Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    double number __gc[] = { 79.31, 47.59, 749.75, 9.07, 9.44 };

    Console::WriteLine(S"Value 1:  {0}", __box(number[0]));
    Console::WriteLine(S"Value 2:  {0}", __box(number[1]));
    Console::WriteLine(S"Value 3:  {0}", __box(number[2]));
    Console::WriteLine(S"Value 4:  {0}", __box(number[3]));
    Console::WriteLine(S"Value 5:  {0}", __box(number[4]));

    Console::WriteLine(S"");
    return 0;
}

This would produce:

Value 1:  79.31
Value 2:  47.59
Value 3:  749.75
Value 4:  9.07
Value 5:  9.44

Press any key to continue
 

Multidimensional Arrays

 

Introduction

The arrays we have used so far are referred to as single or one-dimensional arrays because they use a single group of items that can classified in a single column. In some cases, you may want to divided the list in two or more sections. For example, here is a list of numbers divided in various columns:

  Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Week 1 1 2 3 4 5 6 7
Week 2 8 9 10 11 12 13 14
Week 3 15 16 17 18 19 20 21
Week 4 22 23 24 25 26 27 28

A multi-dimensional array is one that still includes items of the same type but the group is made of sub-divisions following an arrangement an arrangement of your choice.

Two-Dimensional Arrays

Imagine you create two lists of items declared in two variables as follows:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double number1 __gc[] = new Double __gc[5];
    Double number2 __gc[] = new Double __gc[5];

    number1[0] = 643.18;
    number1[1] = 9.64;
    number1[2] = -48.05;
    number1[3] = 14.26;
    number1[4] = 62.55;

    number2[0] = 124.45;
    number2[1] = -62.84;
    number2[2] = 508.06;
    number2[3] = 92.68;
    number2[4] = -44.82;

    Console::WriteLine(S"Value 1:  {0}", __box(number1[0]));
    Console::WriteLine(S"Value 2:  {0}", __box(number1[1]));
    Console::WriteLine(S"Value 3:  {0}", __box(number1[2]));
    Console::WriteLine(S"Value 4:  {0}", __box(number1[3]));
    Console::WriteLine(S"Value 5:  {0}", __box(number1[4]));

    Console::WriteLine(S"Value 6:  {0}", __box(number2[0]));
    Console::WriteLine(S"Value 7:  {0}", __box(number2[1]));
    Console::WriteLine(S"Value 8:  {0}", __box(number2[2]));
    Console::WriteLine(S"Value 9:  {0}", __box(number2[3]));
    Console::WriteLine(S"Value 10: {0}", __box(number2[4]));

    Console::WriteLine(S"");
    return 0;
}

Instead of having two lists that represent the same types of values, you can declare a single array variable and divide its list of items in two. A two-dimensional array is an array made of two lists of items of the same data type. To declare a two-dimensional array, use the following formula:

DataType ArrayName[,] = new DataType[Dimension1,Dimension2];

Once again, you can optionally type the __gc keyword to the left of square brackets. The square brackets to the left of the assignment operator must have only a comma. Inside of the square brackets to the right side of the assignment, you must specify two numbers separated by a comma. The first number indicates the number of lists that the array contains. For a two-dimensional array, this number must be 2. The right value indicates the number of items that each list would contain. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double number __gc[,] = new Double __gc[2,5];

    Console::WriteLine(S"");
    return 0;
}

In this case, the number variable is a two-dimensional array. In other words, the variable represents two lists. Each list contains 5 numbers.

To access a member of the array, type the name of the variable followed by the square brackets. Inside of the brackets, type the zero-based index of the desired list. The first list has an index of 0 while the second list has an index of 1. Then type the comma. On the right side of the comma, type the zero-based index of the member you want to access. Once you have accessed a member of the array, you can either assign it a value or retrieve the value it is currently holding. Here are examples:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double number __gc[,] = new Double __gc[2,5];

    number[0,0] = 643.18;
    number[0,1] = 9.64;
    number[0,2] = -48.05;
    number[0,3] = 14.26;
    number[0,4] = 62.55;

    number[1,0] = 124.45;
    number[1,1] = -62.84;
    number[1,2] = 508.06;
    number[1,3] = 92.68;
    number[1,4] = -44.82;

    Console::WriteLine(S"Value 1:  {0}", __box(number[0,0]));
    Console::WriteLine(S"Value 2:  {0}", __box(number[0,1]));
    Console::WriteLine(S"Value 3:  {0}", __box(number[0,2]));
    Console::WriteLine(S"Value 4:  {0}", __box(number[0,3]));
    Console::WriteLine(S"Value 5:  {0}", __box(number[0,4]));

    Console::WriteLine(S"Value 6:  {0}", __box(number[1,0]));
    Console::WriteLine(S"Value 7:  {0}", __box(number[1,1]));
    Console::WriteLine(S"Value 8:  {0}", __box(number[1,2]));
    Console::WriteLine(S"Value 9:  {0}", __box(number[1,3]));
    Console::WriteLine(S"Value 10: {0}", __box(number[1,4]));

    Console::WriteLine(S"");
    return 0;
}

This would produce:

Value 1:  643.18
Value 2:  9.64
Value 3:  -48.05
Value 4:  14.26
Value 5:  62.55
Value 6:  124.45
Value 7:  -62.84
Value 8:  508.06
Value 9:  92.68
Value 10: -44.82

Press any key to continue

Multi-Dimensional Arrays

A multi-dimensional array is a list of a list of a list, etc. In other words, it is a list that contains other lists while these other lists may contain other lists. For example, a three-dimensional array is one that contains 3 lists; each of the 3 lists contains a certain number of lists; then each list inside contains a list of items.

To declare a multi-dimensional array, in the square brackets, type the number of comma minus the total number of lists. For example, the square brackets of a three-dimensional array would have 2 commas. The square brackets of a 5-dimensional array would have 4 commas. In the square brackets on the right side of the assignment operator must indicate the dimension of each level of list. Consider the following declaration:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;
	
int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double hoursWorked __gc[,,] = new Double[6,3,5];

    Console::WriteLine();
    return 0;
}

In this declaration, the variable represents 6 lists. Each of the 6 lists is made of its own 3 lists. Each of the 3 lists contains 5 items. Another ways to illustrate this is that the array represents 6 months work for a contractor. In each of the six months, the contractor worked for 3 weeks. In each of the 3 weeks, the contractor worked for 5 days.

You can access each member of a multi-dimensional array using its index. In the above example, the first month has an index of 0 while the third month has an index of 2. Everything else is as done for the other dimensional arrays.

The String as an Array and Characters

 

An Array of Characters

In C/C++, you can declare a string variable as an array of characters. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char School[] = "American College of Computer & Information Sciences";

    Console::Write("School Name: ");
    Console::WriteLine(School);

    Console::WriteLine(S"");
    return 0;
}

This would produce:

School Name: American College of Computer & Information Sciences

Press any key to continue

In various previous examples, we used the .NET's String class to declare and process string variables. In some cases, you will need access to one character inside of a string. In C/C++, if you declare a string using an array of characters as done above, to access an individual character, you type the name of the variable followed by square brackets. Inside of the square brackets, you can type the 0-based index of the character you want to access. Remember that the C/C++ char data type is an 8-bit value (to access a character, you should use its Char or __wchar_t type). Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char School[] = "American College of Computer & Information Sciences";
    Char First    = School[0];
    Char Second   = School[9];
    Char Third    = School[20];
    Char Fourth   = School[31];
    Char Fifth    = School[43];

    Console::Write("School Name: ");
    Console::WriteLine(School);
    Console::WriteLine(S"Abbreviation: {0}{1}{2}{3}{4}",
	              __box(First), __box(Second), __box(Third),
	              __box(Fourth), __box(Fifth));

    Console::WriteLine(S"");
    return 0;
}

This would produce:

School Name: American College of Computer & Information Sciences
Abbreviation: ACCIS

Press any key to continue

The Characters of a String Class Value

Many libraries that feature a string class, such as the ATL's basic_string class, the MFC's CString class, or the VCL's AnsiString class provide you the same mechanism (by overloading the [] operator). The Microsoft .NET Framework's String class provides a different functionality. If you declare a String variable and want to access any of its characters, the String class provides a Chars property that uses square brackets to locate a character. This is done using the same approach as above except that you must call the Chars property. Here is an example of how this can be done:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    String* School = "American College of Computer & Information Sciences";
    Char First    = School->Chars[0];
    Char Second   = School->Chars[9];
    Char Third    = School->Chars[20];
    Char Fourth   = School->Chars[31];
    Char Fifth    = School->Chars[43];

    Console::Write("School Name: ");
    Console::WriteLine(School);
    Console::WriteLine(S"Abbreviation: {0}{1}{2}{3}{4}",
	              __box(First), __box(Second), __box(Third),
	              __box(Fourth), __box(Fifth));

    Console::WriteLine(S"");
    return 0;
}

It would produce the same result.

Arrays and Functions

 

An Array as Argument

An array can be passed to a function as argument. An array can also be returned by a function. To specify that a function takes an array as argument, declare the function as you would do for any regular function. In the parentheses of the function, declare the array with the __gc keyword as you have done so far. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

void ShowNumbers(double n __gc[]);

int _tmain()
{
    // TODO: Please replace the sample code below with your own.

    Console::WriteLine(S"");
    return 0;
}

When implementing the function, proceed as you would do normally. If you want to access the members of the array, use the same technique we have used so far, accessing each member of the array by its index. When you call the function from another function, simply pass the name of the array as argument. This would be done as follows:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

void ShowNumbers(double n __gc[]);

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double number[]= { 643.18, 9.64, 48.05, 14.26, 62.55 };

    ShowNumbers(number);

    Console::WriteLine(S"");
    return 0;
}

void ShowNumbers(double Nbr __gc[])
{
    Console::WriteLine(S"Value 1: {0}", __box(Nbr[0]));
    Console::WriteLine(S"Value 2: {0}", __box(Nbr[1]));
    Console::WriteLine(S"Value 3: {0}", __box(Nbr[2]));
    Console::WriteLine(S"Value 4: {0}", __box(Nbr[3]));
    Console::WriteLine(S"Value 5: {0}", __box(Nbr[4]));
}

This would produce:

Value 1: 643.18
Value 2: 9.64
Value 3: 48.05
Value 4: 14.26
Value 5: 62.55

Press any key to continue

If you create a function that takes a non-managed array as argument, you usually would pass an additional argument that carries the size of the array. On the other hand, if you create a function that takes a managed array as argument, since the array would inherit from the Array class, the argument would automatically carry its dimension from the Length property of the Array class. Therefore, with a managed array as argument, you don't have to specify the number of members to the function; the compiler would figure that out.

Returning an Array

Whether in C/C++ or Managed C++, an array is (always) passed as a reference. Although in C/C++, there is no formal way to return an array from a function, because an array is passed as a reference, it is very easy to return an array. Actually, this technique is used in C++ as an accessory, not as a means. Managed C++ formal features the idea of returning an array from a function. Although this is a new feature not available in C/C++, it is very easy to use, so easy that there is very little effort to implement this valuable addition.

To indicate that a function would return an array, if you are only declaring the function, type empty square brackets between the function's parentheses and its semi-colon. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

Double GetNumbers()[];

void ShowNumbers(double n __gc[]);

int _tmain()
{
    // TODO: Please replace the sample code below with your own.

    Console::WriteLine(S"");
    return 0;
}

When defining the function, type the square brackets between the function's parentheses and its opening curly bracket. In the body of the function, you can declare an array, do what you want with it, and then return it as the return value of the function.

When calling a function that returns an array, proceed with the rules you would use for any other function. For example, you can call the function in another and use it as you see fit. You can also assign the function to an array variable in order to initialize the variable. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

Double GetNumbers()[];

void ShowNumbers(double n __gc[]);

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Double no __gc[] = GetNumbers();
    ShowNumbers(no);

    Console::WriteLine(S"");
    return 0;
}

Double GetNumbers()[]
{
    Double number[] = { 643.18, 9.64, 48.05, 14.26, 62.55 };

    return number;
}

void ShowNumbers(double Nbr __gc[])
{
    Console::WriteLine(S"Value 1: {0}", __box(Nbr[0]));
    Console::WriteLine(S"Value 2: {0}", __box(Nbr[1]));
    Console::WriteLine(S"Value 3: {0}", __box(Nbr[2]));
    Console::WriteLine(S"Value 4: {0}", __box(Nbr[3]));
    Console::WriteLine(S"Value 5: {0}", __box(Nbr[4]));
}

 

 


Previous Copyright © 2004-2010 FunctionX, Inc. Next