Question

I'm trying to create a program which outputs the list of prime numbers given an input value, n.

The SieveEratosthenes function that I made: - generates a list of primes over the first n integers - creates storage for the list of generated primes - returns the number of primes generated.

Here's the code in my main function:

int main(){
    int n, i;
    int *primes;

    printf("Number that needs to be prime factorized: ");
    scanf("%d", &n);

    int num_primes;

    num_primes = SieveEratosthenes(n, &primes);
    printf("Generated a list of %d primes\n", num_primes);
    printf("\n");

    for (i = 0; i <= sizeof(num_primes) + 1; i++){
        printf("%d", *primes++);
    }
   printf("\n");

   return 0;
}

Say n = 20; My output is:

'Generated a list of 8 primes

2 3 5 7 11 13'

When my desired output should be '2 3 5 7 11 13 17 19'

My sieve function is working correctly, but I cannot get to print out the entire list of prime numbers in my main function though.

Any help would be much appreciated. Thanks!

Was it helpful?

Solution

You cannot determine the number of primes by computing sizeof(num_primes): that's a compile-time constant, it does not change with the value that you put in num_primes. It looks like your system uses four bytes for an int, so iterating from zero to sizeof+1, inclusive, covers indexes 0, 1, 2, 3, 4, and 5, which is consistent with your observation that six numbers get printed.

If SieveEratosthenes returns the number of primes that it found, your loop should iterate from zero to that number, not to sizeof(num_primes):

for (i = 0; i != num_primes ; i++){
    printf("%d", primes[i]);
}

Note that I changed *primes++ to primes[i]. This is to help you free primes when you are done, and avoid a memory leak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top