存疑:Write a function reverse(s) that reverses the character string s.

本文介绍了一个简单的字符串反转函数实现,并通过示例程序展示了如何逐行反转输入。文章中提供了两个不同的字符串反转方法并分析了其运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

存疑。
Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.

#include <stdio.h>
#define MAXLINE 1000
//declare
int getline1(char line[], int maxline);
void copy(char to[], char from[]);
int reverse(char s[]);
char reverse2(char s[]);

main()
{
    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];
    char demo[80];
    
    
    max=0;
    while((len = getline1(line,MAXLINE))>0)
    {
        /*if (len<=80){
            copy(demo,line);
            printf("the length below 80: %s",demo);
        }
         */
        if (len > max){
            max = len;
            copy(longest,line);
            
        }
    }
    if (max>0)
        printf("\nlongest:%s\n",longest);
    reverse(longest);
    
    printf("reverse:%s\n",longest);
    printf("reverse2:%c\n",reverse2(longest));
    return 0;
}

int getline1(char s[],int lim)
{
    int c = 0,i;
    for (i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
        s[i] = c;
    if (c == '\n')
    {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
    
}
 void copy(char to[], char from[])
{
    int i;
    i = 0;
    while((to[i] = from[i]) != '\0')
        ++i;
}


int reverse(char s[])
{
    char ch;
    int i,j;
    for (j=0;s[j]!='\0';j++){
        
    }
    --j;
    for(i=0;i<j;i++)
    {
        ch = s[i];
        s[i] = s[j];
        s[j] = ch;
        --j;
    }
    return 0;
}

char reverse2(char s[])
{
    int i,j;
    
    for(j=0;s[j]!='\0';j++){
        
    }
    --j;
    char try[j];
    for (i=0;j>=0;++i,--j)
    {
        try[i]=s[j-1];
        
    }
    return try; //Address of stack memory associated with local variable 'try' returned
}

输出:
sighsihsig
shsdifhsi
ghsidh
longest:sighsihsig

reverse:
gishishgis
reverse2:\340
Program ended with exit code: 0

为啥reverse2得出结果是这样呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值