首页 > 解决方案 > C 中的指针和数组。这个概念不是很受欢迎。

问题描述

我正在通过编写一个程序来使用指针检查字符数组是否为回文,从而在 C 中进行练习。一般来说,我对指针仍然有点不确定,但我不知道为什么这个程序不起作用。它为单个字母检查提供正确的输出,但对于多个字符,它总是返回“不是回文”。如果这不是一个好问题,我真的很抱歉,但我真的很想了解我做错了什么,以便我可以更好地掌握指针的概念。

这是程序:

int is_palindrome2(const char *phrase, int length)
{
  char i = 0;
  const char *end;

  phrase = &i;
  end = phrase + length - 1;

  while(phrase < end)
  {
    if((*phrase) != (*end))
    {
      return 0;
    }
    phrase++;
    end--;
  }

  return 1;

}

这就是我从命令提示符得到的输出(第一个测试是订阅,第二个测试是这个函数)

Testing #1: a is a palindrome
Testing #2: a is a palindrome

Testing #1: ab is not a palindrome
Testing #2: ab is not a palindrome

Testing #1: aa is a palindrome
Testing #2: aa is not a palindrome

Testing #1: abcdcba is a palindrome
Testing #2: abcdcba is not a palindrome

Testing #1: madamImadam is a palindrome
Testing #2: madamImadam is not a palindrome

感谢您的时间。

标签: c

解决方案


对于那些感兴趣的人,这里是对正在发生的事情的更直观的解释。

char array[] = "abba";
is_palindrome2(array,4);

array可转换为指向这样的指针

| 'a' | 'b' | 'b' | 'a' | NULL |
   ^
 array

所以当你调用函数时,你可以想象指针指向

| 'a' | 'b' | 'b' | 'a' | NULL |
   ^
 phrase

当你这样做

char i = 0;
phrase = &i;

您实际上重新分配指针以指向其他地方。

| 'a' | 'b' | 'b' | 'a' | NULL |       ...       | 0 |
                                                   ^
                                                phrase

推荐阅读