c - C 中的回文函数,不返回值

标签 c pointers

当我运行这个函数时,我没有得到 1 或 0 的返回值。我不知道为什么,我是指针新手,任何类型的帮助/提示将不胜感激。

int isPalindrome (char * str)
{
    char def[SIZE];
    int length = strlen(str);
    for(int count; count <= length; count++ ){
        def[count] = str[count];
    }

    int c;
    char *begin, *end, temp;

    begin  = str;
    end    = str;

    for (c = 0; c < length - 1; c++)
        end++;

    for (c = 0; c < length/2; c++)
    {        
        temp   = *end;
        *end   = *begin;
        *begin = temp;

        begin++;
        end--;
    }

    for(int count2; count2 <= length; count2++){
        if(str[count2] != def[count2]){
            return 0;
        }
        return 1;
    }
}

该函数被调用为..

 if(isPalindrome(arr) == 1) 
     printf ("\nIs a palindrome.\n\n");

最佳答案

要检查字符串是否为回文,您需要在首先为所有字符分配足够的空间后,通过循环原始字符串并更改顺序来创建一个反向字符串。然后,您可以使用 strcmp 检查反转后的字符串和原始字符串是否相同。

int isPalindrome (char * str)
{
  int length = strlen(str); 
  char* reversed = malloc(sizeof(char)*length); //we allocate enough space for length chars

  for(int i = 0; i < length; i++) {
    reversed[i] = str[length-1-i]; //populate reversed with the chars in str but in the reversed order
  }

  if(strcmp(str,reversed) == 0) //strcmo(a,b) return 0 if they are equal
  {
    free(reversed); //deallocate the space for reversed
    return 1;
  }
  free(reversed); //deallocate the space for reversed
  return 0;
}

关于c - C 中的回文函数,不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634744/

相关文章:

c++ - C++ 中 *& 和 **& 的含义

c - 为什么C程序在循环包含条件时运行速度变慢

c++ - 使用 FFMPEG 和 url_fopen 示例

c - 如何提高 USB cdc 设备的速度?

c - 解释一下这段代码的程序的输出?

c++ - 指针值在分配后不久重置为空

python - 我怎样才能在 C++ 中实现这个结果?数组指向数组

c++ - 对原子操作的最低要求

c - 如何修改 word2vec 代码来构建制表符分隔的短语序列的嵌入?

c++ - 调用 boolean 函数但出现错误 "no matching function to call"?