编辑:问题已解决,由于不正确的while()条件,我正在访问尚未初始化的数据。我已将其从“或”更改为“与”。现在,它可以按预期工作。谢谢!
我试图在C ++中找到两个数组之间的交集。我已经编写了满足我需要的代码,但是当我删除[]数组时,它会中断,从而导致浮点异常。 (除以零?)如何保存所需的值,而又不会导致程序中的内存泄漏?
如果我省略delete []语句,此代码将按照我的预期工作,但我相信这会导致内存泄漏。如果我省略语句greatIntersection = *(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;
答案 0 :(得分:1)
您确实应该使用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;
}
答案 1 :(得分:1)
最大的问题-尽管可能是一个最小的例子,但可能导致错误的原因是,您正在访问的内存尚未初始化。这可能会导致无法预测的行为。
int* factorsa = new int[a];
不会将该数组中的每个int
设置为零-数组的内容实际上可以是任何内容。稍后,在第一个for
循环中,您确实为某些数组位置(而不是全部)设置了值。因此,在最后的for
循环中,您无法知道要输出的内容。这将取决于您要求new
提供的存储位置的大致随机内容。
(此外,如注释所示,您的while
循环条件是错误的。)