#include <stdio.h>
#include <stdlib.h>
//Fibonacci
void fibonacci(int n, int *fibs[n]){
int i;
*fibs[0] = 1;
*fibs[1] = 1;
printf("%d %d ", *fibs[0], *fibs[1]);
for(i=2; i<=n; i ){
*fibs[i] = *fibs[i-1] *fibs[i-2];
printf("%d ", *fibs[i]);
}
}
int main(){
int n, i;
printf("How many fibonacci numbers do you want to enter?: ");
scanf("%d", &n);
int fibs[n];
fibonacci(n, &fibs);
return 0;
}
I was writing a Fibonacci program in this way. The program runs but does not print anything. And I get the error like, [Warning] passing argument 2 of 'fibonacci' from incompatible pointer type
How can I fix this program to run efficiently?
CodePudding user response:
You declared a variable length array
int fibs[n];
In this call
fibonacci(n, &fibs);
the argument has the type int ( * )[n]
.
However the corresponding function parameter
void fibonacci(int n, int *fibs[n]){
has the type int **
(due to adjusting by the compiler the parameter having array type to pointer to the array element type).
So the compiler issues the message.
The function declaration can be much simpler
void fibonacci(int n, int fibs[n]){
And in this case the function is called like
fibonacci(n, fibs);
Of course you will need to change the body of the function.
Pay attention to that this loop
for(i=2; i<=n; i ){
can result in accessing memory outside the passed array when i
is equal to n
because the valid range of indices is [0, n)
.
And the first two Fibonacci numbers are 0
and 1
.
Even in the very beginning of the function
int i;
*fibs[0] = 1;
*fibs[1] = 1;
you need to check whether n is not less than 2.
The function can look for example like
void fibonacci( int a[], size_t n )
{
if ( !( n < 1 ) ) a[0] = 0;
if ( !( n < 2 ) ) a[1] = 1;
for ( size_t i = 2; i < n; i )
{
a[i] = a[i-1] a[i-2];
}
}
and called like
size_t n;
printf("How many fibonacci numbers do you want to enter?: ");
scanf( "%zu", &n );
uf ( n != 0 )
{
int fibs[n];
fibonacci( fibs, n );
}