问题
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