【发布时间】:2021-06-27 20:57:24
【问题描述】:
为什么这个程序没有给出给定字符串computer的反转,尽管length()函数工作正常(当我注释其他代码并且只运行该部分时)并且输出正确但第二个reverse()函数不是给出任何输出。
#include <stdio.h>
#include <string.h>
int length(char *);
char *reverse(char *, int);
int main()
{
char word[] = "COMPUTER";
int count;
count = length("COMPUTER");
printf("%s", reverse(word, count));
}
int length(char *p)
{
int count;
for (count = 0; *(p + count) != '\0'; count++);
return (count);
}
char *reverse(char *p, int count)
{
char temp;
for (int i = 0; i < count / 2; i++)
{
temp = *(p + i);
*(p + i) = *(p - (count - 1) - i);
*(p - (count - 1) - i) = temp;
}
return (p);
}
【问题讨论】:
-
阅读this article 了解调试代码的技巧。
-
你的
- (count - 1)s不应该是+ (count - 1)吗? -
进行基本调试。在调试器中运行您的程序。查看
count的值,查看每一步交换了哪些字符,转储p的内容等。适度调试应该很明显。 -
也许写成
p[i]和p[count - i - 1]会更清楚。
标签: c reverse c-strings pointer-arithmetic function-definition