c - 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
感谢您的时间。
解决方案
对于那些感兴趣的人,这里是对正在发生的事情的更直观的解释。
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
推荐阅读
- latex - 如何修复longtable LATEX的宽度
- arrays - 根据 ARRAY 元素对结果进行排序?
- python - 带有两个数据框的 Dask 折叠
- node.js - 关于使用 SSO Tile 保护关键云代工厂中的 vue js 前端应用程序和节点 js 后端应用程序
- discord.py - Discord.py 机器人重复命令
- python - 加速元胞自动机的绘图
- python - 解析Json响应值Python
- javascript - 将数据从 JSON 输出到模态
- javascript - 节点:`fast-sort` 包 - 排序不是函数
- javascript - 在Angular中使用Input传递数据时如何处理未定义?