将输入的字符串逆置。存在问题,代码如下,求修改!
解决时间 2021-12-23 01:53
- 提问者网友:寂寞撕碎了回忆
- 2021-12-22 07:32
#include
#include
#include
#define N 81
void fun(char *s)
{
char *p = s;
while(*p != '\0')
p++;
p--;
while(*p != '\0')
{
*(s++) = *p;
p--;
}
*s = '\0';
}
main()
{
char a[N];
printf("Enter a string:");
gets(a);
printf("\nThe original string is:");
puts(a);
fun(a);
printf("\nThe string after modified:");
puts(a);
strcpy(a,"Hello world!");
fun(a);
}
最佳答案
- 五星知识达人网友:底特律间谍
- 2021-12-22 07:46
void fun(char *s)
{
char *p = s;
while(*p != '\0')
p++;
p--;
while(*p != '\0')
{
*(s++) = *p;
p--;
}
*s = '\0';
}
这个函数出了问题,经过这个函数处理之后S指针的位置在字符串的结尾,之后你再要PUTS的时候就出现问题了,
void fun(char *s)
{
char *p = s;
char *q = s;
while(*p != '\0')
p++;
p--;
while(*p != '\0')
{
*(s++) = *p;
p--;
}
*s = '\0';
}
s=q;
}
全部回答
- 1楼网友:几近狂妄
- 2021-12-22 09:22
#include
#include
#include
#include
#define N 81
void fun(char *s)
{
char *p = s;
char *q = s;
while(*p != '\0')
{
p++;
}
p--; //p指针移动到s字符串的尾部
while(q < p) //q指向s字符串的头部,p指向s字符串的尾部,每次交换q和p所指地址的值,然后q,p同时向中间移动
{
char temp = *q;
*q = *p;;
*p = temp;
q++;
p--;
}
}
int main()
{
char a[N];
printf("Enter a string: ");
gets(a);
printf("\nThe original string is: ");
puts(a);
fun(a);
printf("\nThe string after modified: ");
puts(a);
strcpy(a,"Hello world!");
puts(a);
fun(a);
puts(a);
system("pause");
return 0;
}
我要举报
大家都在看
推荐资讯