РЕДАКТИРОВАТЬ: проблема была решена, я получал доступ к данным, которые не были инициализированы из-за неправильного условия while (). Я изменил его с ИЛИ на И. Теперь он работает как задумано. Спасибо!
Я пытаюсь найти пересечение между двумя массивами в C ++. Я написал код, который делает то, что я хочу, но когда я удаляю [] массивы, он ломается, что приводит к исключению с плавающей запятой. (Деление на ноль?) Как сохранить требуемое значение, не вызывая утечки памяти в моей программе?
Этот код работает именно так, как я намереваюсь работать, если я опущу операторы delete [], но я считаю, что это приводит к утечке памяти. Он вернет 1, если я опущу выражение Что я могу сделать, чтобы сохранить значение в factora + i и впоследствии удалить массив, чтобы избежать утечки памяти?
const int Fraction::findgcf(int a, int b) const{
a = std::abs(a); //absoute value
b = std::abs(b);
int* factorsa = new int[a]; //dynamic array of ints to store factors of a
int* factorsb = new int[b]; //dynamic array of ints to store factors of b
int numFactorsa = 0;
for(int i = 1; i <= a; i++){//iterate over the ints from 1 to a
if(a % i == 0) {//if we find a factor of a
*(factorsa + numFactorsa) = i;// and append that to the array
numFactorsa++;
}
}
int numFactorsb = 0;
for(int i = 1; i <= b; i++){
if(b % i == 0){
*(factorsb + numFactorsb) = i;
numFactorsb++;
}
}
int biggestIntersection = 1;
int i = 0, j = 0;
while(i < numFactorsa || j < numFactorsb){//while we are in the bounds of the two arrays
if(*(factorsa + i) < *(factorsb + j)){ //if the factor of a is less than the factor of b
i++; //move the index of a up one
} else if (*(factorsa + i) > *(factorsb + j)){ //if the factor of b is less than the factor of a
j++; //move the index of b up one
} else { //otherwise they must be equal
biggestIntersection = *(factorsa + i); //so that is the new biggest intersection between the sets
i++; j++;
}
}
delete [] factorsa;
delete [] factorsb;
return biggestIntersection;