Sieve of Eratosthenes Help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dead Veng
    New Member
    • Apr 2015
    • 1

    Sieve of Eratosthenes Help

    So I've been assigned a program that sieves all non prime numbers from 0-1000. I've written the meat of this code but have a problem. Normally I have a Linux computer with a different compiler, but for this one I'm stuck using Visual Studio 2010. Here's what I have so far. My only problem is the line "int *array = calloc(topval + 1, sizeof(int));" The error is that type void* cannot initialize type int*. Any solutions would be appreciated!!

    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc, char **argv)
    {
    int i;
    int prime;
    int multiple;
    int topval = 1000;
    int count = topval - 1;
    int *array = calloc(topval + 1, sizeof(int));


    /*Marks all elements of the array as possible primes.*/
    for (i=2; i <= topval; i++)
    {
    array[i] = 1;
    }

    /*Marks multiples as non-prime.*/
    for (prime = 2; prime <= topval; prime++)
    {
    if (array[prime])
    for (multiple = 2*prime; multiple <= topval; multiple += prime)
    {
    if (array[multiple])
    {
    array[multiple] = 0;
    count--;
    }
    }
    }

    /*Prints the remaining numbers, which are prime. */
    for (i=2; i <= topval; ++i)
    {
    if (array[i])
    printf("%d ", i);
    }
    printf("\n\n %d primes up to %d found.\n", count, topval);
    exit(0);
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    An int* has to contain the address of an int otherwise the pointer arithmetic won't work. Put any old address in an int* and the program is now ready to crash. For this reason void* can't be assigned to an int*.

    All you have to do is cast the return of calloc to an int*. That way when you crash the compiler will not be responsible.

    Comment

    Working...