简体   繁体   English

C中的回文递归程序

[英]Palindrome recursive program in C

I've figured out on how to work around the string but I can't seem to get it to work.我已经想出了如何解决字符串,但我似乎无法让它工作。 Maybe it's because of the scanf that I'm using.也许是因为我正在使用 scanf 。 Please advise :)请指教 :)

#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;

}

What you're thinking about is the struct hack:你在想的是结构黑客:

typedef struct {
    char s[1];
} String;

int main()
{
    /* allocate 15 extra bytes for the string */
    String *s = malloc(sizeof *s + 15);

This allows you to declare an array of size 1 and then use it as a variable length, but you still have to give it some memory (via malloc) to use it.这允许您声明一个大小为 1 的数组,然后将其用作可变长度,但您仍然必须为其提供一些内存(通过 malloc)才能使用它。 Then you can access it via s .然后您可以通过s访问它。

If you want a variable length string, you should malloc the amount of data you need.如果你想要一个可变长度的字符串,你应该 malloc 你需要的数据量。 If you want to do it a little hacky (and if you're going to compile with Gcc) you can do this:如果你想做一点点hacky(如果你打算用Gcc编译)你可以这样做:

char * str;
scanf("%ms", str);
ok = do_palindrome(str, 0);
printf("%s is palindrome? : %d\n", str, ok);
free(str);
char* str[1] ;

declares an array of one char pointer声明一个由一个字符指针组成的数组

scanf("%c", str[1]);

reads a single char but tries to place it beyond the end of your array (C arrays are zero-based).读取单个字符,但尝试将其放在数组末尾之外(C 数组是从零开始的)。

I think you want to read a string (char array).我想你想读取一个字符串(字符数组)。 You can do this using您可以使用

char str[20]; /* change the array size as required */
scanf("%19s", str); /* read one fewer chars than your array size */
char* str[10] ;
scanf("%s", str);
ok = do_palindrome(str, 0);
printf("%s is palindrome? : %d\n", str, ok);

You are trying to read a string to char type which is wrong and should be of type string.您正在尝试将字符串读取为字符类型,这是错误的并且应该是字符串类型。 Also the subroutine call to do_palindrome should contain base address of str than just first character of the string.此外,对do_palindrome的子例程调用应该包含str基地址,而不仅仅是字符串的第一个字符。

if(length/2 > 0)
    ok = (str[0] == str[length - 1 - offset]) ?
            do_palindrome(++str, ++offset):0;

This statement will run (length - 1) times.此语句将运行(length - 1)次。 When we check for palindrome, we only need to do (length / 2) comparisons.当我们检查回文时,我们只需要做(length / 2)比较。 So I suggest to change code to the following:所以我建议将代码更改为以下内容:

if (length >= 2 && (length / 2) >= offset) {
    ok = (str[0] == str[length - 1 - offset]) ?
            isPalindrome(++str, ++offset) : 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM