简体   繁体   English

我该如何解决这个堆栈溢出错误?

[英]how do i solve this stack overflow error?

i am writing a function in which to check that the given array is a palendrome or not using recursion.我正在写一个 function 来检查给定的数组是一个palendrome还是不使用递归。

int pal(char p[], int i, int j) {
  if (i > j) return 1;
  if (p[i] != p[j]) {
    return 0;
  }
  pal(p, i++, j--);
}

void palTest() {
  char p1[] = "hello";
  char p2[] = "elle";
  int x;
  x = pal(p1, 0, 4);
  if (x == 0)
    printf("p1 is not a palendrom\n");
  else
    printf("p1 is a palendrom\n");
  x = pal(p2, 0, 3);
  if (x == 0)
    printf("p2 is not a palendrom\n");
  else
    printf("p2 is a palendrom\n");
}

void main() { 
    palTest(); 
}

I expected the program to write p2 is a palindrome but it did not print anything.我预计编写 p2 的程序是回文,但它没有打印任何内容。

The function pal function pal

int pal(char p[],int i, int j)
{
if (i > j)
return 1;
    if (p[i] != p[j])
    {
        return 0;
    }
pal(p, i++, j--);
}

has undefined behaviour because it returns nothing in case when not i > j and not p[i].+ p[j].具有未定义的行为,因为它在不是 i > j 且不是 p[i].+ p[j] 的情况下不返回任何内容。

You have to write你必须写

int pal(char p[],int i, int j)
{
if (i > j)
return 1;
    if (p[i] != p[j])
    {
        return 0;
    }
    return pal(p, ++i, --j);
}

Also pay attention to that you have to use the pre-increment and pre-decrement operators.另请注意,您必须使用预递增和预递减运算符。

    return pal(p, ++i, --j);

Otherwise you are passing to a next call of the function pal the same values of i and j .否则,您会将ij的相同值传递给 function pal的下一次调用。

Also the first parameter of the function should have the qualifier const . function 的第一个参数也应该有限定符const

The function can be defined much simpler with using only two parameters. function 的定义更简单,只需使用两个参数。

Here is your program with the updated function definition and its calls.这是您的程序,其中包含更新的 function 定义及其调用。

#include <stdio.h>
#include <string.h>

int pal( const char *s, size_t n )
{
    return n < 2 ? 1 : s[0] == s[n-1] && pal( s + 1, n - 2 ); 
}

void palTest( void )
{
    char p1[] = "hello";
    char p2[] = "elle";
    int x;

    x = pal( p1, strlen( p1 ));
    if (x == 0)
        printf("p1 is not a palendrom\n");
    else
        printf("p1 is a palendrom\n");

    x = pal( p2, strlen( p2 ) );
    if (x == 0)
        printf("p2 is not a palendrom\n");
    else
        printf("p2 is a palendrom\n");
}


int main(void) 
{
    palTest();

    return 0;
}

Instead of the conditional operator in the return statement of the function you could use a logical expression like代替 function 的返回语句中的条件运算符,您可以使用如下逻辑表达式

int pal( const char *s, size_t n )
{
    return ( n < 2 ) || ( s[0] == s[n-1] && pal( s + 1, n - 2 ) ); 
}

Bear in mind that according to the C Standard the function main without parameters shall be declared like请记住,根据 C 标准,不带参数的 function 主要应声明为

int main( void ).

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

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