簡體   English   中英

為什么這個 C 程序沒有給出給定字符串的反轉?

[英]Why this C-program doesn't gives the reverse of given string?

Why this program doesnot gives reverse of the given string computer , though the length() function works fine(when I comment other codes and only run that part) and gives output correct but the second reverse() function is not giving any output.

#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);
 }

這些表達式語句

*(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;
}

程序 output 是

RETUPMOC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM