我已经弄清楚如何解决该字符串,但我似乎无法让它工作。 也许是因为我正在使用 scanf 。 请指教:)
#include<stdio.h>
#include<string.h>
int do_palindrome(char *str, int offset){
int ok = 1;
int length = strlen(str);
if(length/2 > 0)
ok = (str[0] == str[length - 1 - offset])?
do_palindrome(++str, ++offset):0;
return ok;
}
int main(){
int i = 0;
int ok = 0;
char* str[1] ;
scanf("%c", str[1]);
ok = do_palindrome(str[0], 0);
printf("%s is palindrome? : %d\n", str[0], ok);
printf("Finished!");
return 0;
}
最佳答案
你正在考虑的是结构黑客:
typedef struct {
char s[1];
} String;
int main()
{
/* allocate 15 extra bytes for the string */
String *s = malloc(sizeof *s + 15);
这允许您声明一个大小为 1 的数组,然后将其用作可变长度,但您仍然必须给它一些内存(通过 malloc)才能使用它。然后您可以通过s
访问它。
如果你想要一个可变长度的字符串,你应该malloc你需要的数据量。如果你想做一点 hacky(并且如果你要使用 Gcc 编译),你可以这样做:
char * str;
scanf("%ms", str);
ok = do_palindrome(str, 0);
printf("%s is palindrome? : %d\n", str, ok);
free(str);
关于c - C 中的回文递归程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13879075/