I am trying to write a program that prints Fibonacci series of characters by replacing 0 with 'a' and 1 with 'b' and next characters accordingly. I am using another function to recursively find out a particular Fibonacci term and return it as a character pointer.
Code:
#include <stdio.h>#include <string.h>
#include <stdlib.h>
char* FiboS(int);
void D_e() {
printf("Enter fibbonacci series limit\n");
int inp;
scanf("%d", &inp);
char *fibs;
//fibs = (char *)malloc(11);
fibs= FiboS(inp - 1);
printf("%s\n", fibs);
}
char* FiboS(int i) {
if (i == 0)
return "a";
else if (i == 1)
return "b";
char st[10];
st[0] = '\0';
strcat(st, FiboS(i - 1));
strcat(st, FiboS(i - 2));
//printf("%s\n", st);
return st;
}
I used printf() function in FiboS() function to ensure that it was returning proper value and it showed that it was working well.
But the code is giving wrong output, the string stored in char pointer fibs is not the same as returned by FiboS() function. I thought it was because fibs was not allocated any memory so I used malloc() but it made no difference. So I used strcpy() function and it worked.
But I don't understand why fibs was not storing the proper value and what strcpy() does different that it works?
Excuse me if I've missed something obvious, I'm a beginner.