1

I am writing a program to calculate factorial using recursion of main() function.

/* Print factorial */
#include <stdio.h>
#include <stdlib.h>

static char **p;

int main(int argc, char **argv)
{
        int n, rv;
        if (argc < 2) {
                printf("Usage: a.out <value>\n");
                exit(-1);
        }
        n = atoi(argv[1]);
        if (!n) {
                rv = 0;
        } else {
                if (n == 1) {
                        rv = 1;
                } else {
                        n = n - 1;
                        **p = n;
                        main(2, p);
                }
        }
        printf("%d\n", rv);
        return 0;
}

The program compiles using gcc but on execution, I am getting a Segmentation Fault at **p = n. Can somebody help me to modify the above program to get the correct result. Also, what is the logic to capture correct rv value between successive recursive calls in main()?

Chawathe Vipul S
  • 1,636
  • 15
  • 28
manav m-n
  • 11,136
  • 23
  • 74
  • 97

2 Answers2

15

Since you don't seem to care about standard and stuffs, here is an implementation of the recursive main function for printing factorial, that compiles on gcc (I only test on Windows). Since it doesn't follow standard, there is no guarantee that it will compiles on other compiler/platform.

Writing such code for fun is OK, but never let the bad behavior follows into serious coding project or workplace.

/* Print factorial */
#include <stdio.h>
#include <stdlib.h>

char buf[16];

int main(int argc, char **argv)
{
        int n, rv;

        if (argc < 2) {
                printf("Usage: a.out <value>\n");
                exit(-1);
        }

        n = atoi(argv[1]);
        if (!n) {
                rv = 1;
        } else {
                if (n == 1) {
                    rv = 1;
                } else {
                    char *pt = buf;
                    char **pt2 = &pt - 1;

                    sprintf(buf, "%d", n - 1);
                    rv = main(2, pt2) * n;
                }
        }
        printf("%d\n", rv);

        return rv;
}
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
-3

Only operating system can call main when it runs the program. Other than operating system no one can call any function named main. So if want to calculate factorial using recursion then you have to write another function to calculate that recursively and call that function from main.

You can ask why is this? Answer is this is the syntax.

taufique
  • 2,701
  • 1
  • 26
  • 40