|  | 
 
 发表于 2016-7-28 18:58:40
|
显示全部楼层 
| 本帖最后由 小剑剑 于 2016-7-28 19:04 编辑 
 
 楼上正解,我一开始没细看没注意
 第一你可以在findmax函数中就输出
 第二你可以把最长的字符串复制到s,在main函数中输出s
 第三你可以查一下malloc这个函数
 
 
 
 这是我稍微修改了一下的代码,试了两次正确,试试能不能自己按上面思路改回来,在对比一下
 
 复制代码#include<stdio.h>
#include <string.h>         //strcpy函数在这
void input(char s[])
{
        int k=0;
        int c;
    for(;(c=getchar())!='\n';k++)
        {
        s[k]=c;
    }
    s[k]='\0';                                     //读取完成,记得对这个字符数组封口
}
char* findmax(char s[])
{
   int max=0,word_length=0,p=0,k=0;                //这个p是用来记录最长单词的位置
    char *longest_word=malloc(255);              //malloc函数
   for(k=0;s[k]!='\0';k++)
        {
        if(s[k]==' ')
                {                                          //扫到空格,则结算是否为最长的单词
           if(max<word_length)
                   {
               max=word_length;
                p=k;
                word_length=0;                             //这里我放了进来
            }
        }
        else
                {                                           //如果i扫到的不是空格,那么开始计算单词的长度
            word_length++;
        }
   }
if(max<word_length)
        {                                                   //此乃用于最长的单词在结尾的情况
        max=word_length;
        p=k;
        }
    for(p=p-max,k=0;max>0;max--,p++,k++)
        {
        longest_word[k]=s[p];
    }
    longest_word[k]='\0';
    strcpy(s,longest_word);
    printf("The longest word is:%s  在findmax中输出\n",longest_word);    //可以这里输出
    return longest_word;
}
int  main()
{
    char s[255];
    printf("Enter a String,please:\n");
    input(s);
    char* longest_word=findmax(s);
    printf("The longest word is:%s 输出没有释放掉的longest_word\n",longest_word);
    printf("The longest word is:%s  输出s\n",s);
        return 0;
}
 | 
 |