why segmentation fault error in recursive function

会有一股神秘感。 提交于 2020-03-26 03:51:27

问题


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");
}

回答1:


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.



来源:https://stackoverflow.com/questions/59739589/why-segmentation-fault-error-in-recursive-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!