In: Computer Science
I'm having trouble printing a fibonacci sequence using pointers with malloc's to get this output.
now printing with pointers:
0 1 1 2 3 5 8 13 21 34 55 89
Here's my code:
#include <stdio.h>
#include <stdlib.h>
void fib1(int a[]);
void fib2(int* a);
}
int main() {
int arr[2] = {0,1};
int *pointer;
arr[0]=0;
arr[1]=1;
fib1(arr);
return 0;
}
void fib1(int a[]){
printf("printing with arrays:\n");
for(int i=0; i<6; i++){
printf("%d %d ", a[0],a[1]);
a[0] = a[0] + a[1];
a[1] = a[0] + a[1];
}
printf("\n\n");
}
void fib2(int* a){
printf("printing with pointers:\n");
for(int i=0; i<6; i++){
printf("%d %d ", a,a);
}
}
#include <stdio.h>
#include <stdlib.h>
void fib1(int a[]);
void fib2(int* a);
int main() {
int arr[2] = {0,1};
int *pointer;
arr[0]=0;
arr[1]=1;
fib1(arr);
//creating array with size 2 using malloc
pointer=(int *)malloc(2*sizeof(int));
// initiliazing the values 0 and 1
pointer[0]=0;
pointer[1]=1;
fib2(pointer);
return 0;
}
void fib1(int a[]){
printf("printing with arrays:\n");
for(int i=0; i<6; i++){
printf("%d %d ", a[0],a[1]);
a[0] = a[0] + a[1];
a[1] = a[0] + a[1];
}
printf("\n\n");
}
void fib2(int* a){
printf("printing with pointers:\n");
for(int i=0; i<6; i++){
// so here we need to print the 0 th and 1th element
// so we need to use * operator
// to print 1th element we need to add 1 to the pointer
printf("%d %d ", *(a+0),*(a+1));
a[0] = a[0] + a[1];
a[1] = a[0] +a[1];
}
}