0

I've got this code (Simplified example) in my Visual Studio 10:

int myfunc(void)
{
    array <int^>^ temparr=gcnew array<int^>(11);

    for (int i=0; i<11; i++)
    {
         temparr[i]=0;
    }

    temparr[2]=1;  //one of the elements is 1


    for (int i=0; i<11; i++)
    {
         if (!temparr[i]) return 0;   
    }  

    return 1;
}

But when I use this function the output is 1 rather than 0. What can be the problem and how to correct this code?

Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
Bushido
  • 29
  • 6

3 Answers3

2

You have undefined behavior in your code, where you assign integer values to garbage-collected pointers. Why would you even want that? Instead declare temparr as

array <int> temparr(11);

I.e. an array of normal integer values.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Your code does not do what you think it does.

Instead of assigning values to an array of integer, you are assigning them to an array of pointers...

A simple array of integer will solve your problem:

array <int> temparr(11);
//    ^^^^^        ^^^^         
Community
  • 1
  • 1
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
  • Thanks for your answer! But an error occurred after declaring such array: Error C3149: (type) : cannot use this type here without a top-level (char). And after all i have a managed code with managed array. It needs to compare two arrays - managed and unmanaged. Is it possible? – Bushido Sep 24 '13 at 06:23
0

Array of value type (int here) should look like this:

array<int>^ temparr = gcnew array<int>(11);

http://msdn.microsoft.com/en-us/library/vstudio/dtbydz1t%28v=vs.100%29.aspx

Qué Padre
  • 2,005
  • 3
  • 24
  • 39