I was trying to write a function to add primes to a array but my realloc kept failing. Can someone please look at my code and tell me why it is failing?
#include <stdio.h>
#include <stdlib.h>
void makePrimes(int *primes, int *primesLength, int primeTarget);
int isPrime(int input);
int main(void)
{
int *primes = (int *)(malloc(1));
*primes = 2;
int primesLength = 1;
makePrimes(primes, &primesLength, 3);
printf("%d", *(primes + 2));
free(primes);
return 0;
}
//* Finds the prime number that is the prime target number prime
//* (i.e 2 is the zeroth prime)
//! PRIME TARGET COUNTS FROM ZERO BUT PRIMES LENGTH COUNTS FROM 1
void makePrimes(int *primes, int *primesLength, int primeTarget)
{
// do nothing
if (*primesLength >= primeTarget + 1)
return;
int lastValue = *(primes + (*primesLength - 1));
while (primeTarget + 1 != *primesLength)
{
lastValue++;
if (isPrime(lastValue))
{
(*primesLength)++;
primes = realloc(primes, *primesLength * sizeof(int));
*(primes + (*primesLength - 1));
}
}
}
//* Checks if a given integer is prime
int isPrime(int input)
{
if (input == 0 || input == 1)
{
return 0;
}
int testFactor = 2;
for (int iii = 0; iii < (input - 2); iii++)
{
if ((input % testFactor) == 0)
return 0;
testFactor++;
}
return 1;
}
I was expecting it to add one more available element to the array 'primes'. Using a debugger I found that primes was being set to NULL and not running the following line. Thanks.