I need to find all the prime factors of a number. I have written this code, but when I try to reallocate the pointer array in calculatePrimes function using realloc, gcc gives error that i have not allocated the pointer before using realloc. I know I can pass the double pointer and use malloc inside the calculatePrimes function or, use a single pointer and return the value.
Code:
#include "stdio.h"
#include <math.h>
#include <stdlib.h>
void calculatePrimes(int max, int** array){
int size=1, i;
*array[0]=2;
for(i=0; i<max; i++){
if(isPrime(i)){
*array = (int *)realloc(**array, (++size)*sizeof(int));
*array[size-1]=i;
}
}
}
int isPrime(int value){
int i=2, root = sqrt(value);
for(;i<root;i++){
if(value%i==0) return 0;
}
return 1;
}
void main(int argc, char*argv[]){
int input = atoi(argv[1]), numPrimes;
int *primes=(int *)malloc(sizeof(int));
calculatePrimes(input, &primes);
numPrimes=sizeof(primes)/sizeof(int);
printf("%d\n", numPrimes);
free(primes);
}