Click here to Skip to main content
14,922,948 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do you convert the std::vector to system::array?

I dared to do

array<int>^ Arr = gcnew array<int>( stdVec.size());

for(int i=0; i < stdVec.size(); i++)
  Arr[i] = stdVec[i];

There wasn't a compiler error so I dont know if this is actually ok or not. My program crashes at this line though so I'm hoping the reason is the conversion and not something else.

Many thanks as always
Updated 27-Mar-13 12:01pm
[no name] 27-Mar-13 18:05pm
"My program crashes" is not helpful information. Why does it crash? What is the actual error message? What is the exception?
Sergey Alexandrovich Kryukov 27-Mar-13 18:11pm
Exactly. I answered, anyway... :-)
lostandconfused1234 27-Mar-13 18:26pm
Additional information: Index was outside the bounds of the array.

both are declared as int...
lostandconfused1234 27-Mar-13 18:30pm
also I changed my code to that above, so the array size is dependent on the vector size
lostandconfused1234 27-Mar-13 18:33pm
ah fml found the issue.
Sergey Alexandrovich Kryukov 27-Mar-13 18:46pm
OK. Then you use the debugger and see on what index value it happens. Or just look at code.
Please look at my answer, pay attention for my note about 10. This is the sure way to make such bugs. Make sure you have matching number of elements. Or fill in only the number of elements which can fit the size (the size of System::Array is immutable). I don't know which collection happened to be too small, but just sanitize it. Really simple thing...
lostandconfused1234 27-Mar-13 21:42pm
thanks for all your help :-)
Sergey Alexandrovich Kryukov 27-Mar-13 23:16pm
You are very welcome.
Good luck, call again.

1 solution

First of all, don't hard-code your 10, this makes the code completely unsupportable. Ever heard of constants? Do you understand that it could be a variable?

As to the code, it looks correct, but who knows what is stdVec, where it is declared? You should not ask anything about some unknown part of the code. Believe or not, but because of late spring and massive snow melting, my access to your hard drive is somewhat limited. If you declare stdVec correctly as an instance of std::vector of int, your code will work correctly. Please see:[^].

Should be something like
#include <vector>
using namespace std;


vector<int> stdVec;
// only name the object in a humanly manner, is some semantically significant way
// same goes about "Arr" and "i"... :-)

Just for some fun, please see this CodeProject article: Arrays in C++/CLI[^].


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900