Jurafsky Jurafsky - 1 month ago 6
C++ Question

C++ Learning how many numbers are repeated in an array

I'm learning C++. Something in my code isn't working but I don't understand what is the problem. I think is the incrementation of the stat array that counts how many numbers are repeated in T array... How can I fix it? Maybe is the syntax stat[elt]++ that is not correct?

#include <iostream>
#include <cctype>
#include <ctime>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;


int anneeSecu(int T[12][13], int j){
// here I join the 2 numbers of tab (they refer to the year of birth) and I add the number 20, because I know that they were born all after 2000
int a = T[j][1];
int b = T[j][2];

ostringstream oss;
oss << "20" << a << b;
istringstream iss(oss.str());
int ab;
iss >> ab;
int annee = ab;
cout << annee << endl;
return annee;
}




int main(){
int T[12][13]={ {1,1,2,0,2,3,7,1,9,8,2,0,5},
{2,1,3,0,5,8,9,9,0,8,1,0,2},
{2,1,6,0,8,1,9,2,6,5,4,8,7},
{2,1,5,0,6,5,6,3,4,6,0,6,7},
{1,1,5,0,6,5,6,3,4,6,0,7,5},
{2,1,5,0,2,5,6,3,4,6,0,6,7},
{2,1,5,0,6,2,9,1,4,7,1,6,3},
{2,1,4,0,6,2,2,1,4,7,1,6,3},
{2,1,4,0,9,3,5,1,4,7,1,6,3},
{1,1,1,1,2,5,6,1,7,5,0,0,7},
{1,1,1,0,9,5,6,1,7,5,1,0,7},
{2,1,4,1,0,3,5,1,4,7,0,2,2} };


int stat[6]={0,0,0,0,0,0};
for (int i=0;i<12;i++){
int l=anneeSecu(T,i);
**stat[l]++;**
}

return 0;
}


Output and freeze of cmd

2012

Process returned -1073741819 (0xC0000005) execution time : 1.764 s
Press any key to continue.


SOLUTION
The error was in stat[l]++ (because it takes numbers from 0 to 5 only...)
correction => stat[l-2011]++

Answer

There is a problem with this piece of code:

int l=anneeSecu(T,i);
stat[l]++;

Because anneeSecu seams to return a number greather than the lenght of the array. l must be between 0 and 5, or your program will crash.