一个转换字符串的问题,总是不能运行,大家帮我看看,谢了先!

bolognagene 2008-11-03 10:54:46
字符串的反向输出。要求不能用库函数,不能使用数组来暂存指针指向的内容。
编好后总是运行不过去,各位高手们多多指教,小弟先谢了!

#include <stdio.h>
#include <stdlib.h>

void reverse_string(char * strings)
{
char *head = strings;
char *tail = strings;
char tmp;

while(*tail != '\0')
{
tail++;
}
tail--; //points to the tail of this string

while(tail > head)
{
tmp = *head;
head++ = *tail; ---》这个地方不能运行,???
*tail-- = tmp;
}

printf("%s", *strings);

}

void main()
{
char *str = "Hello, World";

reverse_string(str);
}
...全文
88 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunzhonghai666 2008-11-04
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 piaomiaoju 的回复:]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse_string(char * strings)
{
char *head = strings;
char *tail = strings;
char tmp;

while(*tail != '\0')
{
tail++;
}
tail--; //points to the tail of this string

while(tail > head)
{
tmp = *head;
*head++ = *tail; //这个地方不能运行,???
*tail-- = tmp;

[/Quote]
给3楼加分
xuedaoli 2008-11-04
  • 打赏
  • 举报
回复
main里面定义得是指向常量得字符串指针,是不能对进行修改得。
所以你传入这个指针,修改就会出错
yuhudie203 2008-11-04
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 piaomiaoju 的回复:]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse_string(char * strings)
{
char *head = strings;
char *tail = strings;
char tmp;

while(*tail != '\0')
{
tail++;
}
tail--; //points to the tail of this string

while(tail > head)
{
tmp = *head;
*head++ = *tail; //这个地方不能运行,???
*tail-- = tmp;

[/Quote]

VC6下确实会出错 长量不可修改
bolognagene 2008-11-04
  • 打赏
  • 举报
回复
确实是测试程序错误。。。只盯着出错的地方了。。

谢谢各位!
freshui 2008-11-04
  • 打赏
  • 举报
回复
可能是你的测试程序出错了

你不能这样用:reverse_string("abcde");
而只能:
char a[]={"abcde"};

reverse_string(a);

这里的a只能是数组,不能是指针,否则就会告诉你不能修改常量。
因为"abcde"是常量字符串,不能用指针指向它来修改它,只能将他拷贝到数组或者堆栈中修改
insulted 2008-11-04
  • 打赏
  • 举报
回复
3楼正解!
  • 打赏
  • 举报
回复
我测试过你的代码,没问题!
我用Turbo C/C++ 3.0
piaomiaoju 2008-11-03
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse_string(char * strings)
{
char *head = strings;
char *tail = strings;
char tmp;

while(*tail != '\0')
{
tail++;
}
tail--; //points to the tail of this string

while(tail > head)
{
tmp = *head;
*head++ = *tail; //这个地方不能运行,???
*tail-- = tmp;
}
printf("%s",strings);

}

void main()
{
char str[13] = "Hello, World"; //你上面用指针分配的话,指向的字符串常量,不能写.

reverse_string(str);
}
bolognagene 2008-11-03
  • 打赏
  • 举报
回复
不好意思, 粘贴过来的时候 不小心删了个*

黑色的代码应该是
*head++ = *tail;

LS的可以说得详细些吗? 谢谢啦
wuyu637 2008-11-03
  • 打赏
  • 举报
回复
内存有重叠区。你的算法有问题。

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧