存疑。
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得出结果是这样呢?