Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c - Why do I get a segmentation error if `k` is 0?

I want to know why this program gives me a segmentation error. Kindly note that I've solved this problem by changing the value of variable k from 0 to 1. Though it solved my problem, I want to know what happens with the logic/system when k is 0?

#include <stdio.h>
#include <stdlib.h>

int fact_of_nk(int);
int fact_of_k(int);
int fact_of_n(int);

int main()
{
    int fact_n, fact_k, fact_nk, bmu, k = 0, nk;

    for (int n = 1; n <= 10; n++)
    {
        fact_n = fact_of_n(n);
    
        while (k <= n)
        {
            fact_k = fact_of_k(k);
            int nk = (n - k);
            printf("%d ", nk);
            k++;
        }
        k = 0;
        printf("
");
    }
    
    return 0;
}


    int fact_of_n (int number)
{
    if (number == 1)
        return 1;
    else
        return number * fact_of_n(number - 1);
}

    int fact_of_k (int choose)
{
    if (choose == 1)
        return 1;
    else
        return choose * fact_of_k(choose -1);
}

    int fact_of_nk (int choose)
{
    if (choose == 1)
        return 1;
    else
        return choose * fact_of_nk(choose - 1);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You get a stack overflow here because the recursion never ends if you call fact_of_k(0)

int fact_of_k(int choose)
{
  printf("Choose = %d
", choose);   // <<<< add this

  if (choose == 1)
    return 1;
  else
    return choose * fact_of_k(choose - 1);
}

Check this modified function and see what the output is, you'll understand.

Hint for correction: modify slightly this line:

if (choose == 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...