【问题标题】:How can I save a value from a dynamic array in C++?如何在 C++ 中保存动态数组中的值?
【发布时间】:2019-04-12 22:46:09
【问题描述】:

编辑:问题已解决,我正在访问由于不正确的 while() 条件而未初始化的数据。我已将其从 OR 更改为 AND。它现在按预期工作。谢谢!


我试图在 C++ 中找到两个数组之间的交集。我已经编写了可以满足我要求的代码,但是当我删除 [] 数组时它会中断,从而导致浮点异常。 (除以零?)如何保存我想要的值,而不会导致程序中的内存泄漏?

如果我省略 delete[] 语句,此代码将完全按照我的预期工作,但我相信这会导致内存泄漏。如果我省略语句 maxIntersection = *(factorsa + i); 它将返回 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;

【问题讨论】:

  • 你的条件错误while(i &lt; numFactorsa || j &lt; numFactorsb){ 循环只要其中一个计数器在界限内(你想要两个)。但是,要知道这是否会导致问题,请添加 minimal reproducible example
  • new[] 比您在这里发现的价值要麻烦得多。了解如何有效地使用像 std::vector 这样的标准库容器,而不是使用 new[] 对 C 样式数组进行原始分配。在 C++ 中,您 100% 负责内存管理,因此进行手动分配意味着在正确的时间和地点小心添加相应的 delete[] 调用。标准库容器可以为您处理。
  • @tadman 是的,我有一个用向量制作的这个函数的版本,它工作得很好,但是我不应该使用容器来完成这个任务。
  • 需要注意的一点是,您可以像使用数组一样使用指针,而且它更具可读性:*(x + y) 变为 x[y]*(x + y) = z 变为 x[y] = z。这有助于避免由杂乱的代码引起的简单错误。
  • @tadman 很重要的一点,在多维数组方面更容易处理,我不知道两者都产生了相同的编译代码。谢谢

标签: c++ pointers memory-leaks dynamic-arrays


【解决方案1】:

最大的问题——可能是什么导致了你的错误,虽然一个最小的例子会让它更清楚——是你正在访问你没有初始化的内存。这会产生不可预测的行为。

int* factorsa = new int[a]; 不会将该数组中的每个int 设置为零 - 数组的内容实际上可以是任何东西。稍后,在您的第一个 for 循环中,您确实为一些数组位置设置了值,但不是全部。所以在你最后的for 循环中,你无法知道你要输出什么。这将取决于您要求new 提供的内存位置的或多或少的随机内容。

(另外,作为注释,您的 while 循环条件是错误的。)

【讨论】:

  • @G Fetterman,谢谢!将条件从 OR 更改为 AND 解决了我的问题。我确实同意创建具有比我需要的更多空间的数组是危险的,但是我认为我通过跟踪使用变量 numFactorsa 和 numFactorsb 初始化了多少元素来保持在初始化数据的范围内。您是否知道从数学上讲,我可以仅使用存储因子所需的空间量来创建数组?即 10 有 4 个因子,所以我需要 4 个元素的空间。
  • 要回答您关于提前计算因子数量的问题,不,我不知道在没有进行因式分解的情况下如何做到这一点。
【解决方案2】:

你真的应该使用 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;
}

【讨论】:

  • 谢谢,但我特别想在不使用容器的情况下解决这个问题。
猜你喜欢
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多