Home

Arrays and Memory Management

 

Creating a Dynamic Array

If you create an array as we did above, its elements would store in the stack. The compiler would remove them when the program finishes. If you want to be in charge of managing the array, you can store its elements in the native heap. To do this, declare the array as a pointer, using the new operator. Here is an example:

using namespace System;

int main()
{
    __wchar_t * HouseTypes = new __wchar_t[4];

    return 0;
}

To initialize the array, access each element and, using its index, assign it the desired value. In the same way, to access the value of an element, locate it by its index. Here are examples:

using namespace System;

int main()
{
    __wchar_t * HouseTypes = new __wchar_t[5];

    HouseTypes[0] = L'S';
    HouseTypes[1] = L'C';
    HouseTypes[2] = L'S';
    HouseTypes[3] = L'T';
    HouseTypes[4] = L'T';

    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[0]);
    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[1]);
    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[2]);
    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[3]);
    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[4]);

    Console::WriteLine();
    return 0;
}

This would produce:

Type of Propety: S
Type of Propety: C
Type of Propety: S
Type of Propety: T
Type of Propety: T

Press any key to continue . . .

Cleaning After an Array

If you create an array on the native heap as done above, you are responsible for removing the array from memory what you don't need the array anymore. To remove the array and claim the memory it was using, you can use the delete operator with empty square brackets. The formula to follow is:

delete [] ArrayName;

The ArrayName name must be a variable you declared in the native heap using the new operator. Here is an example:

using namespace System;

int main()
{
    __wchar_t * HouseTypes = new __wchar_t[5];
	
    HouseTypes[0] = L'S';
    HouseTypes[1] = L'C';
    HouseTypes[2] = L'S';
    HouseTypes[3] = L'T';
    HouseTypes[4] = L'T';

    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[0]);
    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[1]);
    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[2]);
    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[3]);
    Console::WriteLine(L"Type of Propety: {0}", HouseTypes[4]);

    delete [] HouseTypes;

    Console::WriteLine();
    return 0;
}

If you didn't create the array using the new operator, then don't remove it using the delete operator.

 

 

Previous Copyright © 2007-2012 FunctionX Next