Как я могу сохранить значение из динамического массива в C ++? - PullRequest
0 голосов
/ 13 апреля 2019

РЕДАКТИРОВАТЬ: проблема была решена, я получал доступ к данным, которые не были инициализированы из-за неправильного условия 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;

Ответы [ 2 ]

1 голос
/ 13 апреля 2019

Самая большая проблема - и, вероятно, причина вашей ошибки, хотя минимальный пример прояснит ее - это то, что вы обращаетесь к памяти, которую вы не инициализировали. Это может привести к непредсказуемому поведению.

int* factorsa = new int[a]; не устанавливает каждый int в этом массиве в ноль - содержимое массива может быть буквально любым. Позже, в вашем первом цикле for, вы устанавливаете значения для некоторых положений массива, но не для всех. И поэтому в вашем последнем цикле for у вас нет возможности узнать, что вы собираетесь выводить. Это будет зависеть от более или менее случайного содержимого ячейки памяти, которую вы попросили new предоставить.

(Также, как отмечается в комментарии, ваше условие цикла while неверно.)

1 голос
/ 13 апреля 2019

Вы действительно должны использовать std :: vector. Тогда вам не нужно беспокоиться об уборке.

const int Fraction::findgcf(int a, int b) const{
    a = std::abs(a); //absoute value
    b = std::abs(b);

    std::vector<int> factorsa(a);
    std::vector<int> factorsb(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++;
        }
    }

    return biggestIntersection;
}
...