I casted Malloc because I read and saw videos about dynamic memory where the person would cast malloc, realloc and calloc. Why Should I not ?
Code:
int *new_max_elements = max_elements * 2;int *temp = realloc(fib, sizeof(*fib) * new_max_elements);
This part doubles the fib array,right ? Is there a way to just add one more int memory space for the array with realloc ?
I implemented what you guys wrote but when it reaches the maximum element, the program crashes. I can not undestand why.
This is how it is:
Code:
#include <stdio.h>
#include <stdlib.h>
#define DESIRED_SEQ_LEN 25 // how many terms you want to compute in total
int main(){
int i = 0;
int max_elements = 10; // arbitrary, pick a sensible value for your situation
int *fib = NULL;
fib = malloc(max_elements * sizeof(*fib));
if (fib == NULL)
{
perror("Error allocating memory for fib: ");
exit(EXIT_FAILURE);
}
printf("Fibonacci Sequence is:\n");
fib[0] = 1;
fib[1] = 1;
printf("%d\n", fib[0]);
printf("%d\n", fib[1]);
for (i = 2; i < DESIRED_SEQ_LEN; i++) {
if (i >= max_elements)
{
int *new_max_elements = max_elements * 2;
int *temp = realloc(fib, sizeof(*fib) * (*new_max_elements));
if (temp == NULL)
{
perror("Error reallocating memory for fib: ");
free(fib);
exit(EXIT_FAILURE);
}
max_elements = new_max_elements;
fib = temp;
}
fib[i] = fib[i-1] + fib[i-2];
printf("%d\n", fib[i]);
}
free(fib);
return 0;
}