好的,所以我创建的这个函数使用埃拉托色尼筛法算法来计算所有小于等于 n 的质数。该函数将质数和质数的数量存储在参数中。
当函数退出时,质数应指向一个动态分配的内存块,其中包含所有小于等于 num 的质数。 *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
函数中有一些问题,但我不确定是什么问题。预期输出:
小于或等于19的质数有8个
2 3 5 7 11 13 17 19
我的输出:
2 3 0 5 0 7 0 0 0 11 0 13 0 0 0 17 0 19 0 0
以下是目前已经被指出的3个问题:
1. 错误的删除过程
if (sieve[multiple]) {
数组sieve索引存在偏差
2. (*array) = sieve;
泄漏了刚分配的内存,并让* array 指向一个当函数返回时不存在的局部变量-您将获得一个悬空指针。
3. if(sieve[i] != NULL)应该使用0而不是NULL,因为您没有一个指针数组。
然而,我不太确定如何解决被指出的悬挂指针/内存问题。除此之外,我想知道我的代码中是否还有其他错误,因为我不太确定为什么我的输出数字会添加0...不要担心输出样式不同,只需要额外的数字。如果您能帮助我解决这个问题,谢谢!