Okay, so this function I created uses the Sieve of Eratosthenes algorithm to compute all the primes <= n. This function stores the prime numbers and the count of primes in the parameters.
When the function exits, primes should be pointing to a chunk of dynamically allocated memory that holds all the primes <= num. *count
will have the count of primes.
Here is my function 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;
}
Now, here is the intended output and my output. As you can see, something is wrong within my getPrimes
function but I am unsure as to what.
Intended Output: There are 8 prime numbers less than or equal to 19 2 3 5 7 11 13 17 19 My Output: 2 3 0 5 0 7 0 0 0 11 0 13 0 0 0 17 0 19 0 0
Here are 3 problems that people have pointed out to me so far:
- Wrong delete process
if (sieve[multiple]) {
array sieve index has bias (*array) = sieve;
leaks the just-malloced memory, and lets*array
point to a local variable that ceases to exist when the function returns - you'll get a dangling pointer.if(sieve[i] != NULL)
should use 0, not NULL, you're not having an array of pointers.
However, I'm not too sure how to fix the dangling pointer/memory issue that has been spotted out for me. Besides that, I was wondering if there was anything else within my code that has errors as I am not too sure why my numbers in my output are adding the 0's...don't worry about the different output style, just the extra numbers. Thanks if you can help me out with this!