c - C 中的回文递归程序

标签 c recursion palindrome

我已经弄清楚如何解决该字符串,但我似乎无法让它工作。 也许是因为我正在使用 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/

相关文章:

c - 如何在不知道字符串和字符大小的情况下动态创建C中的字符串数组?

c - if else 递归最差时间复杂度

c - PALIN 的 spoj 上的 c 代码中出现运行时错误 SIGSEGV

C++ 模板图形类,递归

javascript - 使用循环查找下一个回文

java - 如何忽略大小写并考虑字母数字字符

c++ - 如何将 32 位 int 散列为 10 位 int?

c - 从 C 中的套接字文件描述符读取时如何检测分隔符?

c - 阻止分配给数组的理由是什么?

XML 计数 TXT