Pages

Managed array

To create a manged array we should just specify the type and the number of dimensions. The default is a dimension of one. The array keyword, not a standard C++ keyword, is defined in the pseudo namespace cli, that could be used to avoid conflicts.

A managed array is initialized like a standard C++ array:

cli::array^ square = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

cli::array^ square2 = gcnew array(3, 3);
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j)
square2[i, j] = (i * 3) + (j + 1) ;

The dimension of the array is not part of the array type specification, and, as for the other .NET object, once created an array can't change its size. The System::Array::Resize function does not actually resize the passed array, but just create a new one with the new dimensions and then copy the data from the original one.

The initialization of a managed array differs from the one of a standard C++ one in the way that all the element are always initialized to zero and then its default constructor is called, if available.

This post is based on my reading on the book "Expert C++/CLI: .NET for Visual C++ Programmers" by Marcus Heege, APress.

No comments:

Post a Comment