Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization in Managed C++

I wish to declare and initialize a 1D managed array of items.

If it was C# code, I would write it like this:

VdbMethodInfo[] methods = new VdbMethodInfo[] {
    new VdbMethodInfo("Method1"),
    new VdbMethodInfo("Method2")
};

I am trying to write (well, actually, I'm writing a program generate) the same thing in managed C++...

So far I have:

typedef array<VdbMethodInfo^, 1> MethodArray;
// How do I avoid pre-declaring the size of the array up front?
MethodArray^ methods = gcnew MethodArray(2);
methods[0] = gcnew VdbMethodInfo("Method1");
methods[1] = gcnew VdbMethodInfo("Method2");

There are two problems with this:

  1. It's more verbose
  2. It requires me to declare the size of the array up front, which is inconvenient for my code generator

Is there an "array initialization" syntax for GC arrays in Managed C++? What is the correct syntax? Is there a good web link for this and other similar questions?

like image 418
Paul Hollingsworth Avatar asked May 07 '09 14:05

Paul Hollingsworth


People also ask

How do you initialize array in C?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

What is array initialization with example?

int arrTwoDim[3][2] = {6, 5, 4, 3, 2, 1}; Example 8 defines a two-dimensional array of 3 sub-arrays with 2 elements each. The array is declared and initialized at the same time. The first element is initialized to 6, the second element to 5, and so on.

What is managed array?

A managed array is a fixed collection of items that you store in the managed heap.


1 Answers

The C++/CLI array declare & initialize syntax is not dissimilar from that in C#. Here's an example...

array<String^>^ myArray = gcnew array<String^> {"first",  "second"};
like image 174
Martin Avatar answered Oct 12 '22 02:10

Martin