gpt4 book ai didi

c - C 语言中的指针和数组。概念不太明确。

转载 作者:太空狗 更新时间:2023-10-29 15:21:14 25 4
gpt4 key购买 nike

我正在通过编写一个程序来练习 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

关于c - C 语言中的指针和数组。概念不太明确。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52954412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com