简体   繁体   中英

Segmentation error in C after printing a method in a for loop

I have a problem when trying to print the numbers in the n given row of Pascal's triangle in C:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
    int n, k;
    double result1, result2;
    scanf("%d", &n);
    scanf("%d", &k);

    result2 = knumberinnrowofpascal(8, 4);
    printf("%f\n", result2);

    int i = 0;
    for (i; i<n; i++) {
        result2 = knumberinnrowofpascal(n, i);
        printf("%f\n", result2);
    }

    return 0;
}

int combinations(int n, int k) // calculates combinations of (n,k).
{
    if (k == 0)
        return 1;
    else if (k > n)
        return 0;
    else
        return (combinations(n - 1, k) + combinations(n - 1, k - 1));
}

int knumberinnrowofpascal(int n, int k)
{
    double rightmultipier, leftmultiplier, result;
    rightmultipier = (double)(n + 1 - k) / k;
    leftmultiplier = (double)combinations(n, k - 1);
    result = (double)leftmultiplier * rightmultipier;
    return result;
}

The function "knumberinnrowofpascal" works, I've tested it above (the 4th element in the 8th row ). The problem is when I try to print these results in a for loop.

rightmultipier = (double)(n + 1 - k) / k;

This will fail if k is 0. And even if it didn't, it would on the next row, because you would have infinite recursion there.

Change:

int i = 0;
for (i; i <= n; i++) {

to

int i;
for (i=1; i <= n; i++) {

I made two improvements there. I fixed the bug and moved the initialization to the for header.

return (combinations(n - 1, k) + combinations(n - 1, k - 1));

when k!=0 and n<k , you recurse with combinations(n-1,k) . Decrementing n in this recursion does not change k!=0, and it certainly does not make n > k until it overflows, which means you are in a practically infinite recursion and it segfaults.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM