Jumping straight to code, this is what I would like to do:
size_t len = obj->someLengthFunctionThatReturnsTypeSizeT();
array<int>^ a = gcnew array<int>(len);
When I try this, I get the error
conversion from size_t to int, possible loss of data
Is there a way I can get this code to compile without explicitly casting to int? I find it odd that I can’t initialize an array to this size, especially because there is a LongLength property (and how could you get a length as a long – bigger than int – if you can only initialize a length as an int?).
Thanks!
P.S.: I did find this article that says that it may be impractical to allocate an array that is truly size_t, but I don’t think that is a concern. The point is that the length I would like to initialize to is stored in a size_t variable.
Managed arrays are implemented for using
Int32as indices, there is no way around that. You cannot allocate arrays larger thanInt32.MaxValue.You could use the static method
Array::CreateInstance(the overload that takes aTypeand an array ofInt64), and then cast the resultingSystem::Arrayto the appropriate actual array type (e.g.array<int>^). Note that the passed values must not be larger thanInt32.MaxValue. And you would still need to cast.So you have at least two options. Either casting:
or this (no need to cast len, but the result of
CreateInstance):Personally, i find the first better. You still might want to check the actual size of len so that you don’t run into any of the mentioned errors.