Click to See Complete Forum and Search --> : Help with array and run-time error


BballJosh
March 4th, 2009, 06:38 PM
I am trying to display a list of words in random order. To do this I am generating a random number and then checking it against an array to see if the number has been used already. I am basically self taught so things may be inefficient/not the correct way to do things, but it works and that's all I really care about. So anyways, when I execute this code:

int number = Words->Length;
System::Random^ RandNumber = gcnew System::Random();
int RandNum = RandNumber->Next(0,number);
//Check to make sure word has not been used yet
if(CheckNum->Length==Words->Length)
CheckNum->Clear;
for(int c=0;c<Words->Length;c++)
{
if(CheckNum[c]==RandNum)
{
RandNum = RandNumber->Next(0,number);
c=0;
}
}
int CheckInt = CheckNum->Length;
CheckNum[CheckInt] = RandNum;

I get the error: Object reference not set to an instance of an object. I'm not sure what I'm doing wrong. Any ideas? And I should probably define variables up top I know but I just add them when I need them when I'm troubleshooting, I can clean it up later. Oh and CheckNum is defined higher up in the code as: array<int^>^CheckNum;

Thanks for the help

Lindley
March 4th, 2009, 06:43 PM
That's managed code, you'll have better luck in the managed C++/CLI forum.

Algorithmically, the correct way to generate a number of unique values is to use a set data structure. This could be a hash table or a tree, depending on what you have readily available. (The std::set in native (unmanaged) C++ is tree-based.)

BballJosh
March 4th, 2009, 06:55 PM
Oh sorry, could an admin please move this to the managed section? And thanks for the help Lindley.

Yves M
March 5th, 2009, 01:29 AM
[ moved ]

darwen
March 5th, 2009, 05:40 PM
(1) Learn to use the debugger, and step through your code. It'll be easy to identify which line is causing the exception, and why by watching the variables (just hover your mouse over each variable and it'll tell you what value it is).

(2) At a guess I'd say CheckNum isn't assigned - but as you haven't included the definition of CheckNum I can't say for certain.

Darwen.

BballJosh
March 5th, 2009, 10:12 PM
The definition is in my first post.

BballJosh
March 15th, 2009, 12:51 AM
bump