PingSpike
Lifer
I'm sure this is something stupid, but it doesn't make sense to me. I'm trying to find the mode in a list of values passed to a function. It isn't complete yet, but once I get to the inner for loop I get an access violation message at run time with VC++. If I hover over the variables i and truelength at this point it shows "766" which I assume is the current value. Which makes no sense to me at all.
Code:
#include <iostream>
using namespace std;
void printarray (int *list, int length)
{
int *candidates;
int *counts;
candidates = new int[length]; //must be some problem with these...can't write to them?
counts = new int[length]; //??
//int candidates [10];
//int counts [10];
int truelength = 0;
int choice = 0;
//candidates[0] = list[0]; //add first item to list of candidates
//counts[0] = 1; // set that items count to 1
for (int n=0; n<length; n++)
{
for (int i=0; i<=truelength; i++)
{
if ( i == truelength ) // no matches found, this is new
{
candidates[truelength] = list[n];
counts[truelength] = 1;
truelength = truelength + 1; //update count
}
else
if ( list[n] == candidates[i] ) // we found a match in the current list
{
counts[i] = counts[i] + 1;
break; //i = truelength; // force loop escape
}
}
}
for (int j=1; j<truelength; j++)
{
if (counts[j] > counts[choice])
choice = j;
}
// cout << *(list+n) << ",";
cout << candidates[choice];
cin >> choice;
//clean up
delete [] candidates;
delete [] counts;
}
int main ()
{
int inputs[8] = { 1, 2, 3, 4, 5, 8, 9, 9 };
int length = 8;
printarray(inputs, length);
return 0;
}