简体   繁体   English

如何在C ++中从动态数组保存值?

[英]How can I save a value from a dynamic array in C++?

EDIT: The problem has been solved, I was accessing data that had not been initialized because of the incorrect while() condition. 编辑:问题已解决,由于不正确的while()条件,我正在访问尚未初始化的数据。 I have changed it from OR to AND. 我已将其从“或”更改为“与”。 It now works as intended. 现在,它可以按预期工作。 Thanks! 谢谢!


I am trying to find the intersection between two arrays in C++. 我试图在C ++中找到两个数组之间的交集。 I have written code that does what I want, but when I delete[] the arrays it breaks resulting in a floating point exception. 我已经编写了满足我需要的代码,但是当我删除[]数组时,它会中断,从而导致浮点异常。 (Division by zero?) How can I save the value I want, without causing a memory leak in my program? (除以零?)如何保存所需的值,而又不会导致程序中的内存泄漏?

This code works exactly how I intend it to work if I omit the delete[] statements, but I believe this causes a memory leak. 如果省略delete []语句,此代码将完全按照我的预期工作,但是我认为这会导致内存泄漏。 It will return 1 if I omit the statement biggestIntersection = *(factorsa + i); 如果我省略语句greatIntersection = *(factorsa + i),它将返回1; What can I do to save the value at factorsa + i and subsequently delete the array to avoid a memory leak? 我该怎么做才能将值保存在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;

You really should be using std::vector. 您确实应该使用std :: vector。 Then you don't have to worry about cleaning up. 然后,您不必担心清理。

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;
}

The biggest problem - and likely what is causing your error, though a minimal example would make it clearer - is that you're accessing memory you haven't initialized. 最大的问题-尽管可能是一个最小的示例,但最大的问题可能是导致错误的原因-您正在访问尚未初始化的内存。 This can produce unpredictable behavior. 这会产生不可预测的行为。

int* factorsa = new int[a]; doesn't set each int in that array to zero - the contents of the array could be literally anything. 不会将该数组中的每个int设置为零-数组的内容实际上可以是任何东西。 Later, in your first for loop, you do set the values for some array locations, but not all of them. 稍后,在第一个for循环中,您确实为某些数组位置(但不是全部)设置了值。 And so in your final for loop, you have no way of knowing what you're going to output. 因此,在最终的for循环中,您无法知道要输出的内容。 It will depend on the more-or-less random contents of the memory location you asked new to provide. 这将取决于您要求new提供的存储位置的或多或少的随机内容。

(Also, as a comment notes, your while loop condition is wrong.) (此外,如注释所示,您的while循环条件是错误的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM