Dynamic array with unknown size

I want to write a C program where the user enters 2 numbers a and b.

0 <a <INT_MAX

a <b <INT_MAX

The program checks how many primes are between a and b and stores them all in a dynamic array.

For the function, mallocI need the size of the array, which means I must first check all the numbers, if they are prim numbers, to get the size of the array, then use malloc()and then check all the numbers again to fill the array. Is there any way to make this run faster and not do the same thing twice?

for (int i = a; i <= b; i++)
{
  if (check_if_prime(i) == 0)
    size++;
}
primze_numbers = malloc(size*sizeof(int));
int j = 0;
for (int i = a; i <= b; i++)
{
  if(check_if_prime(i) == 0)
  {
    prime_numbers[j] = i;
    j++;
  }
}
+4
source share
2 answers

, .

: ( realloc) , .

Real size - Space size
    0            0
    1            1
    2            2
    3            4
    4            4
    5            8
    6            8
    7            8
    8            8
    9            16
    10           16
    ...          ...

, , .

+2

++ - std::vector, .

0

Source: https://habr.com/ru/post/1539400/


All Articles