Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays of strings in Managed C++

I'm trying to write an application in Managed C++, but I cannot work out how to declare an array of strings.

String^ linet[];

throws an error

'System::String ^' : a native array cannot contain this managed type

So I suppose there's a different way to do this for managed data types. What exactly is it?

like image 474
Jonathan Prior Avatar asked Jun 15 '09 10:06

Jonathan Prior


People also ask

Can you make an array of strings in C?

In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array.

How do you declare an array of strings?

A String Array is an Array of a fixed number of String values. A String is a sequence of characters. Generally, a string is an immutable object, which means the value of the string can not be changed. The String Array works similarly to other data types of Array.

What is managed array?

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

Can arrays store strings?

Answer: Yes. Just like arrays can hold other data types like char, int, float, arrays can also hold strings. In this case, the array becomes an array of 'array of characters' as the string can be viewed as a sequence or array of characters.


2 Answers

Do you really mean Managed C++? Not C++/CLI?

Assuming you're actually using C++/CLI (because of the error message you posted), there are two ways to do this:

array<String^>^ managedArray = gcnew array<String^>(10);

will create a managed array, i.e. the same type as string[] in C#.

gcroot<String^>[] unmanagedArray;

will create an unmanaged C++ array (I've never actually tried this with arrays - it works well with stl containers, so it should work here, too).

like image 200
Niki Avatar answered Sep 28 '22 07:09

Niki


http://www.codeproject.com/KB/mcpp/cppcliarrays.aspx

That should have all the answers you need :)

When working with Managed C++ (aka. C++/CLI aka. C++/CLR) you need to consider your variable types in everything you do. Any "managed" type (basically, everything that derives from System::Object) can only be used in a managed context. A standard C++ array basically creates a fixed-size memory-block on the heap, with sizeof(type) x NumberOfItems bytes, and then iterates through this. A managed type can not be guarenteed to stay the same place on the heap as it originally was, which is why you can't do that :)

like image 45
cwap Avatar answered Sep 28 '22 09:09

cwap