免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2048 | 回复: 7
打印 上一主题 下一主题

[函数] 指针问题 求助 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-04-16 02:19 |只看该作者 |倒序浏览
把字符串中的‘:’转换成'\0'。大家帮忙调一下
void colon_conversion1(char *buf) {
        char *p;
        int colons = 0;

        p = buf;
        while ((p != NULL) && (colons < 5)) {
                if (*p == ':') {
                        *p = '\0';
                        colons++;
                }
                p++;
        }
}

void colon_conversion2(char *buf) {

    int colons = 0;

   while ((*buf != '\0') && (colons < 5)) {
    if (*buf == ':') {
        *buf = '\0';                                                                    colons++;
    }
     buf++;
   }
}

int main()
{
        char *str = "h:el:lo :wo:rd:!";
        fputs(str,stdout);
        fputs("\n",stdout);

        colon_conversion1(str);
        colon_conversion1(str);

        fputs(str,stdout);
        fputs("\n",stdout);
        return 0;
}
分别调用两个函数打印的结果都是
[root@localhost testm]# ./ces
h:el:lo :wo:rd:!
段错误 (core dumped)

论坛徽章:
0
2 [报告]
发表于 2010-04-16 02:21 |只看该作者
colon_conversion1(str);
// colon_conversion2(str);
调用1或者2

论坛徽章:
0
3 [报告]
发表于 2010-04-16 07:31 |只看该作者
int main()
{
char *str = "h:el:lo :wo:rd:!";
        fputs(str,stdout);
        fputs("\n",stdout);


先修改为
char str[] = "h:el:lo :wo:rd:!";
吧,再出问题再说了

论坛徽章:
0
4 [报告]
发表于 2010-04-16 09:16 |只看该作者
先修改为
char str[] = "h:el:lo :wo:rd:!";
吧,再出问题再说了
sh19871122 发表于 2010-04-16 07:31


因为字符串指针,是常量....

论坛徽章:
0
5 [报告]
发表于 2010-04-16 12:34 |只看该作者
因为字符串指针,是常量....
iidioter 发表于 2010-04-16 09:16

难道这位兄弟有疑问?
那只能用readelf看看了

论坛徽章:
0
6 [报告]
发表于 2010-04-16 12:38 |只看该作者

论坛徽章:
0
7 [报告]
发表于 2010-04-19 17:35 |只看该作者
char *str = "h:el:lo :wo:rd:!";====这是字符串常量不能修改。
企图修改常量字符串的内容而导致运行错误 ,可能就是segment fault。

你看下这篇文章吧。

http://theflashblog.spaces.live. ... 640608B54!207.entry

论坛徽章:
0
8 [报告]
发表于 2010-04-19 17:36 |只看该作者
回复 4# iidioter


    你说对了,只是  太言简意赅。呵呵
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP