【问题标题】:Why this C-program doesn't gives the reverse of given string?为什么这个 C 程序不给出给定字符串的反转?
【发布时间】: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


【解决方案1】:

这些表达式语句

*(p + i) = *(p - (count - 1) - i);
*(p - (count - 1) - i) = temp;

不正确,

看来你的意思

*(p + i) = *(p + ( count - 1 ) - i);
*(p + (count - 1) - i) = temp;

也代替这个语句

count = length("COMPUTER");

这样写会更符合逻辑

count = length( word );

这是一个演示程序。

#include <stdio.h>

size_t length( const char * );
char * reverse( char *, size_t );
 
int main(void) 
{
    char word[] = "COMPUTER";
    size_t count = length( word );

    puts( reverse( word, count ) );

}

size_t length( const char *p )
{
    size_t count = 0;

    while ( *( p + count ) != '\0' ) ++count;
    
    return count;
}

char * reverse( char *p, size_t count )
{
    for ( size_t i = 0; i < count / 2; i++ )
    {
        char temp = *( p + i );
        *( p + i ) = *( p + count - 1 - i );
        *( p + count - 1 - i ) = temp;
    }
    
    return p;
}

程序输出是

RETUPMOC

【讨论】:

    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多