为什么这个 C 程序不给出给定字符串的反转?
Why this C-program doesn't gives the reverse of given string?
虽然 length()
函数工作正常(当我评论其他代码并且只评论 运行 那部分时),但为什么这个程序不给出给定字符串 computer
的反转并给出输出正确,但第二个 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) != '[=10=]'; 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);
}
这些表达式语句
*(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 ) != '[=14=]' ) ++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
虽然 length()
函数工作正常(当我评论其他代码并且只评论 运行 那部分时),但为什么这个程序不给出给定字符串 computer
的反转并给出输出正确,但第二个 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) != '[=10=]'; 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);
}
这些表达式语句
*(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 ) != '[=14=]' ) ++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