Mitchell Faas
Mitchell Faas

Reputation: 440

How to set up a variable length array for a prime-sieve algorithm in C?

I'm completely new to C, only really having had experience with Python in the past, so please forgive my ignorance here.

I'm trying to implement the prime-sieve algorithm of Eratosthenes in C. This algorithm recursively discards all multiples of a given number until the last number you wish to know is found. Specifically, the program will have an input n, and will output all prime numbers smaller than n.

To achieve this, I thought to create an array of length n and recursively cycle over this array, discarding integers I no longer care about (by changing them to 0).

The problem I found however, is that c does not allow for an array of variable length. I thought I outsmarted this rule for a little bit by doing this trick:

void Sieve(int n) {
    int prime[n+1];
}

But sadly, even variables given to functions aren't okay.

Hence my question: How can I initiate such an array in C?

Upvotes: 1

Views: 365

Answers (1)

Sandy
Sandy

Reputation: 903

You can use dynamic memory allocation:

int* prime;
prime = malloc(sizeof(int)*n);

then use it as a regular array e.g. prime[n-1]

Upvotes: 2

Related Questions