【发布时间】:2013-03-20 16:50:24
【问题描述】:
好的,所以我创建的这个函数使用埃拉托色尼筛算法来计算所有素数
当函数退出时,素数应该指向一块动态分配的内存,其中包含所有素数*count 将有素数的计数。
这是我的函数getPrimes:
void getPrimes(int num, int* count, int** array){
(*count) = (num - 1);
int sieve[num-1], primenums = 0, index, fillnum, multiple;
//Fills the array with the numbers up to the user's ending number, num.
for(index = 0, fillnum = 2; fillnum <= num; index++, fillnum++){
sieve[index] = fillnum;
}
/* Starts crossing out non prime numbers starting with 2 because 1
is not a prime. It then deletes all of those multiples and
moves on to the next number that isnt crossed out, which is a prime. */
for (; primenums < sqrt(num); primenums++) //Walks through the array.
{
//Checks if that number is NULL which means it's crossed out
if (sieve[primenums] != 0) {
//If it is not crossed out it starts deleting its multiples.
for (multiple = (sieve[primenums]);
multiple < num;
multiple += sieve[primenums]) {
//Crossing multiples out
//and decrements count to move to next number
sieve[multiple + primenums] = 0;
--(*count);
}
}
}
int k;
for(k=0; k < num; k++)
printf("%d \n", sieve[k]);
printf("%d \n", *count);
array = malloc(sizeof(int) * (num + 1));
assert(array);
(*array) = sieve;
}
现在,这是预期的输出和我的输出。如您所见,我的 getPrimes 函数中有问题,但我不确定是什么。
到目前为止,人们向我指出了以下 3 个问题:
- 错误的删除过程
if (sieve[multiple]) {数组筛子索引有偏差 -
(*array) = sieve;泄漏刚刚分配的内存,并让*array指向一个在函数返回时不再存在的局部变量 - 你会得到一个悬空指针。 -
if(sieve[i] != NULL)应该使用 0,而不是 NULL,因为你没有指针数组。
但是,我不太确定如何解决已为我发现的悬空指针/内存问题。除此之外,我想知道我的代码中是否还有其他错误,因为我不太清楚为什么我的输出中的数字添加了 0...不要担心不同的输出样式,只需担心额外的数字.谢谢你能帮我解决这个问题!
【问题讨论】:
标签: c primes sieve-of-eratosthenes sieve dangling-pointer