Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- *
- abfact.c
- S. Edward Dolan
- Wednesday, November 20 2019
- */
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- char* fibo(int n) {
- char* out;
- if (n == 1) {
- /*
- `out' has to be malloc'd because the caller of fibo() must call
- free(), marked with ### below. The caller may be main() or the final
- `else' below.
- */
- out = malloc(sizeof(char) * 2); /* two bytes that `out' points to */
- strcpy(out, "b"); /* out => ['a', 0] */
- }
- else if (n == 2) {
- out = malloc(sizeof(char) * 2);
- strcpy(out, "a");
- }
- else {
- /*
- This loosely does what Python does for you:
- return fibo(n-1) + fibo(n-2)
- */
- char* s1 = fibo(n - 1), *s2 = fibo(n - 2); /* caller */
- out = malloc(sizeof(char) * (strlen(s1) + strlen(s2) + 1));
- out = strcat(strcpy(out, s1), s2);
- /*
- You no longer need s1 and s2 because their characters were copied to
- out, which the caller does need.
- */
- free(s1); /* ### */
- free(s2); /* ### */
- }
- return out;
- }
- int main(int argc, char** argv) {
- int i = 1, n = 5;
- if (argc > 1)
- n = atoi(argv[1]);
- while (i < n) {
- char* v = fibo(i++); /* caller */
- printf("%ld\n", strlen(v));
- /* puts(v); */
- free(v); /* ### */
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement