Home

Managed Arrays

 

Introduction

A managed array is a fixed collection of items that you store in the managed heap. When the array is not in used anymore, the garbage collector would decide about this and would remove it from memory. To create a managed array, you use the following formula:

array<DataType> ^ ArrayName = gcnew array<DataType>(Size)

The keywords array and gcnew are required. The ^ operator is required. The DataType specifies the type of values that the elements will hold. The ArrayName is the name of the variable. The Size is the number of elements in the array. Here is an example:

array<double> ^ values = gcnew array<double>(4);

To initialize this type of array, you can access each one of its elements and, using its index, assign it the desired value. In the same way, to retrieve the value of an element, access it by its position. Here are examples:

using namespace System;

int main()
{
    array<double> ^ values = gcnew array<double>(5);

    values[0] = 550500;
    values[1] = 115000;
    values[2] = 425000;
    values[3] = 350000;
    values[4] = 314800;

    Console::WriteLine(L"Value: {0}", values[0]);
    Console::WriteLine(L"Value: {0}", values[1]);
    Console::WriteLine(L"Value: {0}", values[2]);
    Console::WriteLine(L"Value: {0}", values[3]);
    Console::WriteLine(L"Value: {0}\n", values[4]);

    return 0;
}

This would produce:

Property Value: 550500
Property Value: 115000
Property Value: 425000
Property Value: 350000
Property Value: 314800

Press any key to continue . . .

You can also initialize the array when creating it. To do this, create a comma-separated list of the value of the elements, put that list between curly brackets and assign it to the variable. Here is an example:

using namespace System;

int main()
{
    array<double> ^ values = gcnew array<double>(5)
	  { 550500, 115000, 425000, 350000, 314800 };

    Console::WriteLine(L"Value: {0}", values[0]);
    Console::WriteLine(L"Value: {0}", values[1]);
    Console::WriteLine(L"Value: {0}", values[2]);
    Console::WriteLine(L"Value: {0}", values[3]);
    Console::WriteLine(L"Value: {0}\n", values[4]);

    return 0;
}

In the same way, you can declare as many arrays as you want in a program.

Practical LearningPractical Learning: Introducing Arrays

  1. To start a new program, launch Microsoft Visual C++ 2005
  2. On the main menu, click File -> New -> Project... (or File -> New Project...)
  3. On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
  4. In the Name box, replace the string with RealEstate12 and click OK
  5. To create a source file, on the main menu, click Project -> Add New Item...
  6. In the Templates list, click Source File (.cpp)
  7. In the New box, type Exercise and click Add
  8. In the empty file, type:
     
    using namespace System;
    
    int main()
    {
        array<__wchar_t> ^ HouseTypes = gcnew array<__wchar_t>(4)
    	{ L'S', L'C', L'S', L'T' };
        array<int> ^ Bedrooms = gcnew array<int>(4) { 5, 2, 3, 3 };
        array<Byte> ^ Stories = gcnew array<Byte>(4) { 3, 1, 3, 2 };
        array<double> ^ Bathrooms = gcnew array<double>(4)
    	{ 3.5, 1, 2.5, 1.5 };
        array<bool> ^ HasGarage = gcnew array<bool>(4)
    	{ true, true, false, false };
        array<double> ^ Values = gcnew array<double>(4)
    	{ 550500, 115000, 425000, 350000 };
    
        Console::WriteLine(L"House Catalog");
        Console::WriteLine(L"===================================================");
        Console::WriteLine(L"Type Bedrooms Stories Bathrooms Garage    Value");
        Console::WriteLine(L"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
        for(int house = 0; house < 4; house++)
        {
            Console::WriteLine(L"  {0}\t{1}\t{2}\t{3}\t{4}\t{5:F}",
    					   HouseTypes[house], Bedrooms[house],
    					   Stories[house], Bathrooms[house],
    					   HasGarage[house], Values[house]);
            Console::WriteLine(
    		L"---------------------------------------------------");
        }
    
        Console::WriteLine();
        return 0;
    }
  9. To execute the application, on the main menu, click Debug -> Start Without Debugging
     
    House Catalog
    ===================================================
    Type Bedrooms Stories Bathrooms Garage    Value
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
      S     5       3       3.5     True    550500.00
    ---------------------------------------------------
      C     2       1       1       True    115000.00
    ---------------------------------------------------
      S     3       3       2.5     False   425000.00
    ---------------------------------------------------
      T     3       2       1.5     False   350000.00
    ---------------------------------------------------
    
    Press any key to continue . . .
  10. Close the DOS window

An Array of Handles

If you are creating an array of primitive types and you want to treat each element as a handle, declare its type with the ^ operator before >. Here is an example:

array<int ^> ^ Stories = gcnew array<int ^>(5);

When initializing the array, you can assign the right value to each member of the array. Here is an example:

using namespace System;

int main()
{
    array<int ^> ^ Stories = gcnew array<int ^>(5);

    Stories[0] = 4;
    Stories[1] = 2;
    Stories[2] = 3;
    Stories[3] = 1;
    Stories[4] = 3;

    Console::WriteLine(L"Levels: {0}", Stories[0]);
    Console::WriteLine(L"Levels: {0}", Stories[1]);
    Console::WriteLine(L"Levels: {0}", Stories[2]);
    Console::WriteLine(L"Levels: {0}", Stories[3]);
    Console::WriteLine(L"Levels: {0}\n", Stories[4]);

    return 0;
}

The reason this works is that the compiler is able to figure out the type and amount of memory that an element would need to store its value. If you initialize an element with a confusing value, the compiler would display an error and the program would not compile. Consider the earlier array of property values and change the array to a handle to double:

using namespace System;

int main()
{
    array<double ^> ^ values = gcnew array<double ^>(5);

    values[0] = 550500;
    values[1] = 115000;
    values[2] = 425000;
    values[3] = 350000;
    values[4] = 314800;

    Console::WriteLine(L"Value: {0}", values[0]);
    Console::WriteLine(L"Value: {0}", values[1]);
    Console::WriteLine(L"Value: {0}", values[2]);
    Console::WriteLine(L"Value: {0}", values[3]);
    Console::WriteLine(L"Value: {0}\n", values[4]);

    return 0;
}

The only change we made was to change how memory is allocated for the array elements. This program would not compile and it would throw the following error:

error C2440: '=' : cannot convert from 'int' to 'System::Double ^'

The reason is that, when the compiler tries to store a value in the memory allocated for an element, it finds out that the value is not appropriate for the type of element. There are two ways you can solve this program. You can initialize each element with an appropriate value, in this case a double-precision value. Here are examples:

using namespace System;

int main()
{
    array<double ^> ^ values = gcnew array<double ^>(5);

    values[0] = 550500.00;
    values[1] = 115000.00;
    . . .

    Console::WriteLine(L"Value: {0}", values[0]);
    Console::WriteLine(L"Value: {0}", values[1]);
    Console::WriteLine(L"Value: {0}", values[2]);
    Console::WriteLine(L"Value: {0}", values[3]);
    Console::WriteLine(L"Value: {0}\n", values[4]);

    return 0;
}

This time, the program will compile. Another solution, probably clearer, is to allocate memory for each element using the gcnew operator and calling the constructor of the data type to specify the value held by the element. Here are examples:

using namespace System;

int main()
{
    array<double ^> ^ values = gcnew array<double ^>(5);

    values[0] = 550500.00;
    values[1] = 115000.00;
    values[2] = 425000.00;
    values[3] = gcnew double(350000);
    values[4] = gcnew double(314800);

    Console::WriteLine(L"Value: {0}", values[0]);
    Console::WriteLine(L"Value: {0}", values[1]);
    Console::WriteLine(L"Value: {0}", values[2]);
    Console::WriteLine(L"Value: {0}", values[3]);
    Console::WriteLine(L"Value: {0}", values[4]);

    Console::WriteLine();
    return 0;
}

Remember that you can also initialize an array in its own curly brackets. Here is an example:

using namespace System;

int main()
{
    array<double ^> ^ values = gcnew array<double ^>(5)
    {
	550500.00,
	115000.00,
	425000.00,
	gcnew double(350000),
	gcnew double(314800)
    };

    Console::WriteLine(L"Value: {0:C}", values[0]);
    Console::WriteLine(L"Value: {0:C}", values[1]);
    Console::WriteLine(L"Value: {0:C}", values[2]);
    Console::WriteLine(L"Value: {0:C}", values[3]);
    Console::WriteLine(L"Value: {0:C}", values[4]);

    Console::WriteLine();
    return 0;
}

Practical LearningPractical Learning: Using an Array of Handles

  1. To create and use an array of handles, change the program as follows:
     
    using namespace System;
    
    int main()
    {
        . . . No Change
    
        array<bool> ^ HasGarage = gcnew array<bool>(4)
    	{ true, true, false, false };
        array<double ^> ^ Values = gcnew array<double ^>(4)
        {
    	gcnew double(550500.00),
    	gcnew double(115000.00),
    	gcnew double(425000.00),
    	gcnew double(350000.00)
        };
    
         . . . No Change
    
        Console::WriteLine();
        return 0;
    }
  2. Execute it to see the result
  3. Close the DOS window and return to your programming environment
 

Previous Copyright © 2007-2012 FunctionX Next