I've got a loop that looks for prime numbers in an interval of numbers. What I want to do is place the prime numbers in a dynamical array, hence its starting length is 1, and when I find the second number I want to reallocate memory to make the array able to hold 2 numbers instead of one and so on. The code I have looks like this:
int *arr = new int[1];
int count = 0;
for(int i = 0; i <= x; i++) // (x is a value given by the user)
{
if (is_prime(i))
{
realloc(arr,(sizeof(int)*(count + 1)));
count++;
arr[count] = i;
}
}
I'm sure I'm supposed to use the realloc function to do this but the above code doesn't work and I'm not used to memory management while programming.
NOTE: I am aware of vectors, I want to do this with a dynamical array.
reallocyou should be coding inCand notC++.