急问!!函数中改变传入的字符串问题!!

jackey_option 2008-12-07 08:10:30
char *Trim(char *s)//清除字符串前后的空格字符
{
char *s1,*s2;
s1=s2=s;
while(*s1==' ') s1++;
s=s1;
while(*s1) s1++;
s1--;
while(*s1==' ') s1--;
*++s1='\0';//将会出错的地方
return s;
}
void main()
{
char strs[]=" hello, andy! ! ";
char *pchar;
pchar=Trim(strs);
cout<<pchar<<endl;
}
假如修改main()函数中代码:
char *str=" hello,andy! ! ";
str=Trim(str);
cout<<str<<endl;
则会在运行是报错!!
问题:为什么定义为字符串指针变量时,在函数中不能改变原来字符串的值呢?
而是数组时,在函数中又能够改变原来字符串的值了?

请大家解答啊!!谢谢!!
...全文
165 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
jackey_option 2008-12-07
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 hairetz 的回复:]
因为char *str=" hello,andy! ! "; 是默认为const的吧。
记得这种赋值方式只能在声明的同时定义。不能之后单独定义。
[/Quote]

说的对

同时,我觉得这种赋值方式并一定要在声明的同时定义
即还可以这样:
char *str;
str=" hello,andy!! ";
事实上,这样的定义是正确的。~~
jackey_option 2008-12-07
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 rejoice914 的回复:]
C/C++ code
char *Trim(char *s)//清除字符串前后的空格字符
{
char *s1,*s2;
s1=s2=s;
while(*s1==' ') s1++;
s=s1;
while(*s1) s1++;
s1--;
while(*s1==' ') s1--;
*++s1='\0';//将会出错的地方 *s1不可修改吧!
return s;
}
void main()
{
char strs[]=" hello, andy! ! "; //
char *pchar;
pchar=Trim(strs);
cout < <pchar < <endl;
}




这里用while我没看…
[/Quote]

第一个while用来找到第一不为空格符的字符位置
第二个用来使指针指向结尾
第三个用来找到倒数第一个不为空格符的字符位置
bill830711 2008-12-07
  • 打赏
  • 举报
回复
该函数还有个问题,如果只是把s指向非空格开始的地方,到时候删除的时候可能要小心了
一般是把非空格的往前移动(相当于把前面的空格去掉,而不是返回第一个指向非空格的指针)
lann64 2008-12-07
  • 打赏
  • 举报
回复
char strs[]=" hello, andy! ! "; //在栈里分配空间,初始化成后面的字符串。

char *str=" hello,andy! ! "; //将后面的字符串放到常量区,并用指针初始化定义的str。

一个给字符串分配了空间,一个没有分配。

rejoice914 2008-12-07
  • 打赏
  • 举报
回复

char *Trim(char *s)//清除字符串前后的空格字符
{
char *s1,*s2;
s1=s2=s;
while(*s1==' ') s1++;
s=s1;
while(*s1) s1++;
s1--;
while(*s1==' ') s1--;
*++s1='\0';//将会出错的地方 *s1不可修改吧!
return s;
}
void main()
{
char strs[]=" hello, andy! ! "; //
char *pchar;
pchar=Trim(strs);
cout < <pchar < <endl;
}


这里用while我没看明白,用if不行吗?
  • 打赏
  • 举报
回复
因为char *str=" hello,andy! ! "; 是默认为const的吧。
记得这种赋值方式只能在声明的同时定义。不能之后单独定义。
killbug2004 2008-12-07
  • 打赏
  • 举报
回复
日经
char *str=" hello,andy! ! "; 这样str是字符常量指针字符常量是不允许改变的

定义成这样就可以了char str[]=" hello,andy! ! ";

69,373

社区成员

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

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