I am trying to return a pointer to a dynamically created array of ints from a function. Right now the array values should be the same as their index. so data[3] = 3.... Eventually this array will be filled with primes from some sieve code that I have already written, but I need to get this function framework working. It currently compiles without warning, but seg faults. Thanks to dwks who wrote nearly all of this code.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int *getPrimes(int *count, int max)
{
int size = 10; // this keeps track of how many elements are allocated
int *array = malloc(size * sizeof(*array));
*count = 0; // this keeps track of how many elements are used, so *count <= size at all times
int x;
for( x = 0 ; x < max ; x++ )
{
// assume x needs to be added to the array.
if(*count + 1 > size)
{
// not enough space.
size *= 2;
array = realloc(array, size * sizeof(*array));
}
array[*count] = x;
*count ++;
}
return array;
}
int main(void)
{
int n = 300;
int count;
int *data = getPrimes(&count, n);
printf("data0 is %i", data[0]);
return 0;
}