0

My question is about dynamic memory allocation and pointer arithmetic.I have a function that is called in the main function and it should fill the array with n longs and populate them with a Fibonacci sequence dynamically. my function is below but it doesn't appear to give me the correct output.

long* make_fib_array(long n){

int i;
long *fib;  
fib = (long*)malloc(sizeof(long)*n);
if (fib == NULL){
    printf("ERROR: Out of memory\n");
return NULL;}


*fib = 0;
*(fib +1) = 1;
for (i=2;i<n;i++);{
    *(fib +i) = *(fib + (i-1)) + *(fib + (i-2));}     

for(i=0;i<n;i++){
    printf("%ld\n",*(fib + i));}


return fib;}

using a value of the values of 0 and 1 print fine but the values after this are very large and not expected. I suspect it is something to do woth my pointer arithmetic but im not sure what it is.

tribo32
  • 333
  • 3
  • 15

1 Answers1

1

Just remove ; after for loop brackets:

From

for (i=2;i<n;i++);{

to

for (i=2;i<n;i++) {
Morpheus
  • 377
  • 2
  • 9