为什么递归函数中存在分段错误 [英] why segmentation fault error in recursive function

查看:89
本文介绍了为什么递归函数中存在分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我编写了这段代码,目的是查看天气是否为palyndrom,执行时出现段错误,您能帮上忙吗?这是查看单词是否为palyndrom的好方法吗?
提前

Hi I wrote this code and the aim is to see weather a word is palyndrom or not, I get a segmenation fault while executing, may you help? Is it a good way to see if a word is palyndrom? thx in advance

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

int m=1;

void palindromi();

int main (int argc, char *argv[]) {

    int len, a, i=0;

    if (argc != 2)
        exit(0);

    len = strlen(argv[1]);
    a = len-1;
    printf("La lunghezza della parola e' %d\n",len);

    palindromi(argv[1], len, a, i);

    return 0;
}

void palindromi(char *parola, int len, int a, int i) {

    if (i < len/2){
        if (parola[i] == parola[a]) {
            palindromi(parola, len, a--, i++);
        }
        else
            m = 0;
    }

    if (m == 1)
        printf("La parola e' palindroma\n");
    if (m == 0)
        printf("La parola non e' palindroma\n");
}


推荐答案

用于pre-increment和post的操作顺序-increment in a function arguments?,在函数调用之后后进行后递增和递减。

在您的情况下, palindromi(parola ,len,a--,i ++); 与永远调用相同无限循环。

应该是 palindromi(parola,len,--a,++ i); ,在递归之前正确更改值呼叫。

As stated in Order of operations for pre-increment and post-increment in a function argument?, post increment and decrement are done after the function call.
In your case, palindromi(parola, len, a--, i++); is the same as calling forever palindromi(parola, len, a, i); which is an infinite loop.
It should have been palindromi(parola, len, --a, ++i);, correctly changing the value before the recursive call.

这篇关于为什么递归函数中存在分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆