c - Not printing desired output for sieve of eratosthene -


i'm trying create program outputs list of prime numbers given input value, n.

the sieveeratosthenes function made: - generates list of primes on first n integers - creates storage list of generated primes - returns number of primes generated.

here's code in main function:

int main(){     int n, i;     int *primes;      printf("number needs prime factorized: ");     scanf("%d", &n);      int num_primes;      num_primes = sieveeratosthenes(n, &primes);     printf("generated list of %d primes\n", num_primes);     printf("\n");      (i = 0; <= sizeof(num_primes) + 1; i++){         printf("%d", *primes++);     }    printf("\n");     return 0; } 

say n = 20; output is:

'generated list of 8 primes

2 3 5 7 11 13'

when desired output should '2 3 5 7 11 13 17 19'

my sieve function working correctly, cannot print out entire list of prime numbers in main function though.

any appreciated. thanks!

you cannot determine number of primes computing sizeof(num_primes): that's compile-time constant, not change value put in num_primes. looks system uses 4 bytes int, iterating 0 sizeof+1, inclusive, covers indexes 0, 1, 2, 3, 4, , 5, consistent observation 6 numbers printed.

if sieveeratosthenes returns number of primes found, loop should iterate 0 number, not sizeof(num_primes):

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

note changed *primes++ primes[i]. free primes when done, , avoid memory leak.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -